As part of the work done on RVM during the Ruby Summer of Code, One of the things I worked to add was a fairly comprehensive Ruby version of the bash API.
Since then, the Ruby API has been used to build a couple of small projects and tools but it still maintains relatively undocumented.
Today, I’m going to introduce the basics of working with the Ruby API, starting by introducing the fundamental concepts you need to know and then going on to cover how the most common example of it’s use (rvm gemset support in passenger) works under the hood.
Getting started
First off, you’re going to want to make sure you actually have the Ruby API installed. If you have a remotely recent (e.g. newer than 6 or so months) copy of rvm, you’ll already have a copy – Otherwise, you’re going to need to update your rvm install using rvm update.
To load the API, open up irb and type the following:
# First, find where rvm is installed
rvm_path = File.expand_path(ENV['rvm_path'] || '~/.rvm')
# Secondly, add the ruby library to the load path
$LOAD_PATH.unshift File.join(rvm_path, 'lib')
# Finally, actually load rvm
require 'rvm'
Once said code has been executed, you should have access to RVM constant in your irb session. The method we use to require it means that it is loaded from the currently installed version of rvm so you don’t have to deal with issues related to different versions between rvm itself and the Ruby API.
The bare basics
The ruby api works on the concept of a rvm ‘environment’ – Essentially, you can think of them as the equivalent of a shell instance – They keep track of instance variables, have their own ruby / gemset selection and are sandboxed (for the most part) from other environments. Creating a new environment is as simple as doing the following in your ruby code:
env = RVM.environment 'ree'
Or, alternatively, you can pass a block and it will be called with the environment as an argument. Along side this, you have RVM.environments, which accepts multiple ruby names and calls the block with each environment.
For convenience sake, RVM exposes RVM.current, an environment that defaults to the currently loaded gemset (e.g. if you open irb in rbx@rails3, it will be an environment using rbx@rails3).
As an added bonus, when you call an undefined method on RVM, we automatically use method missing to call it on RVM.current – Hence, If RVM::Environment#some_instance_method exists, you can use RVM.some_instance_method to call it in the current environment object.
Working with environments
So, now that you know how to get environment object, you need to know how to use it. In the simplest form, the Ruby API mirrors the command line program by translating:
rvm command action arg1 arg2
Into:
env.command_action arg1, arg2
With the library automatically taking care of converting arguments (e.g. a hash as the last value will be converted to arguments to the program).
As an example, to call rvm list strings, One would use env.list_strings. Likewise, rvm use becomes env.use and so on and so forth. In these cases, use switches the environments ruby – not the running ruby itself.
One of the added features in the Ruby API is that use and gemset_use have alternatives with a bang (use! and gemset_use!) that will switch the currently loaded ruby’s gemset (by changing GEM_PATH and GEM_HOME and then telling rubygems about the change) - raising an exception if it’s for a different ruby installation. This switch makes it possibly to dynamically switch your ruby applications gemset whilst running.
Of course, dealing with a direct port of the API isn’t always nice when you’re writing a lot of code env.alias_list feels clunky compared to most ruby code and some of the tools are rough around the edges. With this in mind, the ruby api offers wrappers for situations where this becomes noticeable, e.g env.aliases will return a more ruby-like wrapper for the alias command that lets you do things such as env.alias.all, env.aliases.create and so on. In some cases (e.g. env.list_*), the wrappers add features (such as expanding strings) that aren’t found in the bash API via the wrapper.
A real world example
With that said and done, it’s time to look at a real world example. In this case, the most commonly-used example of the rvm ruby API – A use of passengers support for a config/setup_load_paths.rb file which lets passenger automatically load .rvmrc files. When a compatible ruby is detected, the file will automatically switch the gemset on the fly – In essence, letting passenger work with the one-gemset-per-application philosophy we advocate when dealing with rvm.
For references sake, the rvm portion of the code is:
if ENV['MY_RUBY_HOME'] && ENV['MY_RUBY_HOME'].include?('rvm')
begin
rvm_path = File.dirname(File.dirname(ENV['MY_RUBY_HOME']))
rvm_lib_path = File.join(rvm_path, 'lib')
$LOAD_PATH.unshift rvm_lib_path
require 'rvm'
RVM.use_from_path! File.dirname(File.dirname(__FILE__))
rescue LoadError
# RVM is unavailable at this point.
raise "RVM ruby lib is currently unavailable."
end
end
Line by line, this code essentially:
- Checks that we’re loading it in an RVM ruby – rvm always sets the
MY_RUBY_HOMEenvironment variable when using wrappers and we ensure that “rvm” is part of said variables value. - It begins a begin-rescue-end section of code to load rvm – Giving us a nice error message if rvm isn’t available.
- Based on my ruby home, We find the location of your rvm install (as
rvm_pathmay or may not be set at this point). - We add the rvm ruby lib directory to the load path
- We require the API
Up until this point, it is almost exactly like our original example. Where it differs is the next line:
RVM.use_from_path! File.dirname(File.dirname(__FILE__))
Knowing what I wrote about earlier, we know this is the same as:
RVM.current.use_from_path! File.dirname(File.dirname(__FILE__))
Which, if we look under the hood, does:
RVM.current.use! RVM.current.tools.path_identifier(path)
Expanding this again using what we learnt earlier, we know that RVM.current.use! will take a given ruby string (e.g. ree@rails3) and attempt to switch out the gemset when the ruby versions match. Continuing on, we know RVM.current.tools.path_identifier is roughly the same as RVM.current.tools_path_identifier – a line which takes a path and, taking into account .rvmrc files, returns the identifier (e.g. ree@rails3) we’d get if we had changed into the given directory from the command line.
Putting it all together, the ruby api essentially just finds out which identifier the given path should use (by loading a projects .rvmrc in the given environment), checks they’re for the same ruby install (to avoid issues with binary gems) and finally switches out the GEM_HOME and GEM_PATH variables for the current process, letting your application use a different gemset.
In short, under the hood it simple finds out the gemset details and updates your application to switch them out similar to how rvm would from the command line.
More examples
We’ve only covered the basics of of the ruby api – For the most part, everything implemented in the bash API is supposed to be (except where it lags behind in terms of updates) exposed via the Ruby API in a simple, consistent manner. In practice, this has primarily been used for things like infinity_test and various CI-related work which make working with multiple rubies easier from ruby applications.
I’d ultimately love to see it used more for tools built around rvm – e.g. a web interface for managing a servers system wide install and exposing it over HTTP. Lastly, because it’s written in Ruby, if you’ve ever wanted to contribute to rvm but have felt apprehensive due to the fact it’s written in shell script, the rvm ruby API is a good place to start.
Spakman
Dec 14, 2010
Nice timing for me finding out about this. I’ve still never used RVM but, without digging too deeply, this API looks like it should make integrating it into my shell (https://github.com/Spakman/urchin) much easier.
I expected to have to write this API myself – thanks!
damnpepe
Dec 14, 2010
Hello, I think that in first code example there should be File.expand_path instead of File.expand.
Good read anyway
Darcy Laycock
Dec 15, 2010
@Spakman Excellent – let me know how you find working with it.
@damnpepe Indeed there was supposed to be – cheers for pointing that out. I’ve fixed it now.
Hedgehog
Mar 8, 2011
RVM.list_strings gives this error:
https://gist.github.com/859919
Is this a known bug? Any suggestions
Darcy Laycock
Mar 9, 2011
@Hedgehog – Not a known bug; I just tried with the current gem of the ruby library and the latest head of rvm (to upgrade, use “rvm get head”) and it appeared to work find on 1.8.7 and 1.9.2 for me?
hedgehog
May 11, 2011
I think that turned out to be an issue in using the JetBrains/RubyMine IDE – haven’t confirmed it yet since I moved onto some other tasks.
Thanks for the API – very useful.