This weekend I decided to work on a utility to… well, we’ll get back to the original purpose in the next post.

I began by staring at an empty console window and trying to remember how to start a project in Ruby, then consulting the blog post I wrote the last time I tried something like this. Oh, right!

$ bundler gem --test-rspec currency_utils

Followed by the usual, change into the directory and commit the initial files.

$ cd currency_utils
$ git commit -m "Initial commit of generated project"

And just to check that all is well with the setup:

$ bundle exec rspec

Finished in 0.00179 seconds (files took 0.43379 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/currency_utils_spec.rb:8 # CurrencyUtils does something useful

That’s expected. The generated project includes a test to check that the project has a version, which passes, and one that asserts it “does something useful,” which fails.

Next I added a class and a method to the generated module, and I wanted to try it out in irb or pry. But it wasn’t there.

$ irb
> CurrencyUtils
NameError: uninitialized constant CurrencyUtils

Okay… in the Rails console this all Just Works and I don’t have to think about it. But people develop gems all the time, so this must be a solved problem.

I searched, but Google and Stack Overflow did not have anything that helped.

I tried a few things like loading the lib/currency_utils.rb file, but that choked on the require statement that is generated into that file. I tried it in a ‘plain’ (non gem) project with just the code in a file, and that worked okay. But I need it to work in a project where the code is under ‘lib’.

I have a vague grasp of require and $LOAD_PATH in Ruby, but not enough to know the answer to this, so I traipsed off to the #ruby channel on Freenode IRC and suffered the usual abuse to learn that what I needed was to use the -I switch when starting irb and to specify the lib directory so that it will be on the loadpath.

Now I can do:

$ irb -I lib
> require 'currency_utils'
=> true
> CurrencyUtils::VERSION
=> "0.1.0"

But this still doesn’t get me to the point where typing irb Just Works the way rails console does. This article gets us a bit further:

$ irb -I lib -r currency_utils

Now lib is on the load path and I don’t have to type require 'currency_utils' after irb starts up.

I have a hard time believing people type that out all the time though.

For now I’ve got it aliased in ~/.bash_profile – this assumes that the directory name matches the project name, meaning if you’re in the whatever directory there is a file named lib/whatever.rb:

alias irb='irb -I lib -r ${PWD/*\/}'

How do YOU use irb (or pry) when working on a gem project?


On Twitter, Greg Vaughan had the answer I was looking for: bundle console

$ bundle console
Resolving dependencies...
> CurrencyUtils::VERSION
=> "0.1.0"

So now I have that aliased as bc just like bundle exec is aliased as be.