Ruby Gem Development with IRB
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!
Followed by the usual, change into the directory and commit the initial files.
And just to check that all is well with the setup:
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.
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 load
ing 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:
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:
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
:
How do YOU use irb (or pry) when working on a gem project?
Update
On Twitter, Greg Vaughan had the answer I was looking for: bundle console
So now I have that aliased as bc
just like bundle exec
is aliased as be
.