Dr. Nic recently put together a screencast of adding a Ruby snippet to TextMate. This particular snippet makes a class definition using the filename as the default classname. I always enjoy listening to Dr. Nic, so definitely check out the ‘cast.

I used to love TextMate, but I can’t use it anymore since I’m working on multiple platforms. Emacs is my editor of choice now and I can’t say that I’m missing anything.

Dr. Nic’s example was interesting enough that I decided to replicate it using yasnippet and elisp. As you’ll see in the video, TextMate supports shelling out to bash or Ruby to do complex processing of snippets. Yasnippet supports inline elisp to handle complex snippets and allows shelling out to other processes when necessary.

Usage

If you’re editing a file named foo.rb and use the snippet, it will create a class definition for Foo. If you’re editing a file named currency_converter.rb, it will create a class named CurrencyConverter.

Installation

Put the following code into a file named kls in the ruby-mode directory. Then use it like you would any other yasnippet.

#name : class ... end
#contributor : hitesh <hitesh.jasani gmail.com>
#contributor : Roberto H.
# --
class ${1:`(let ((fn (capitalize (file-name-nondirectory
				(file-name-sans-extension
		(or (buffer-file-name)
			(buffer-name (current-buffer))))))))
	(replace-regexp-in-string "_" "" fn))`}
$0
end

Update (2010-01-31): Thanks to some good input this routine has been improved to handle multiple underscores in the filename.