We are a software consultancy based in Berlin, Germany. We deliver
high quality web apps in short timespans.

Upstream Agile GmbH Logo

Sublime Text 2 with RVM on OSX

July 30, 2011 by Alex

While everyone is still waiting for Textmate 2 from time to time an interesting alternative pops up. One of those alternatives is version 2 of Sublime Text.

One of the key features of a text editor for programming is being able to run my tests/specs from within the editor. Sublime offers a build command that runs a ruby file and shows the output within the editor. Not as pretty as TextMate with its HTML output but it’s something to start with.

The problem is that Sublime simply runs ruby, which in most cases will invoke the ruby interpreter that ships with OSX. Instead I want it to use my project specific .rvmrc file and run the Ruby version and Gemset I’ve specified for RVM. It took me a while to figure this out and I think there must be an easier way but this works:

Create a file ~/bin/rvm_ruby that looks like this:

#!/usr/bin/env ruby

file = File.expand_path(ARGV[0] || (STDERR.puts('you must specify a ruby file'); exit(-1)))
dir = File.dirname file
while dir.size > 1
  if File.exist?(dir + '/.rvmrc')
    exec("source \"$HOME/.rvm/scripts/rvm\"; cd #{dir}; ruby #{file}")
  else
    dir = dir.sub(/\/[^\/]*$/, '')
  end
end

puts "Could not find any .rvmrc above #{file}"
exit -1

Make it executable by running chmod +x rvm_ruby. Now edit the file ~/Library/Application Support/Sublime Text 2/Packages/Ruby/Ruby.sublime-build and change it to look like this:

{
    "cmd": ["/Users/$YOUR_USERNAME$/bin/rvm_ruby", "$file"],
    "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
    "selector": "source.ruby"
}

That’s it. Now when you edit a Ruby file and press Cmd-B it runs the file with the correct Ruby version.

By the way, you can do the same with the RSpec package.

Hello Explorer!

You’ve found our very old Website Archive (2007-2012). It’s a bit out of date, but we love looking back at how it all started - and how far we’ve come since then! We’re now fully focused on building our coworking management product, Cobot.

Take a look →