Rails Console
When developing in Rails I spend a lot of time in the console. If you are a Rails developer you know you can fire it up in rails 2.3.x with
1
| |
Once in the console you can do lots of things like run ActiveRecord queries
1 2 | |
Ick. That’s not hugely readable.
Hirb to the rescue
Hirb is a gem that makes the console more user friendly. In hirb’s words is is
A mini view framework for console/irb that’s easy to use, even while under its influence. Console goodies include a no-wrap table, auto-pager, tree and menu.
Returning to our previous version hirb makes the output useful
1 2 3 4 5 6 7 8 | |
Nice. We’ve got the query and a concise, readable view.
So how do we get it to work? Documentation is available round the web but takes a little piecing together so here it is in one place.
Installing Hirb
This is easy enough. Just run
1
| |
To use hirb in Rails when you are using the console add a few lines to .ircbc.
1
| |
Then the following to the file
1 2 3 4 5 6 7 | |
Save and quit.
Now go into the console and run a query. You’ll see that the output should be changed to use hirb. If your records have lots of columns you’ll likely see
1
| |
So you’ll need to customise it..
Customising Hirb
You can set which columns are shown in the console and other options in a hirb.yml file. In the /config folder of your rails app create a file called hirb.yml. A feature that I really like is that you can specify which columns show for models. So for this example I can specify what shows for the User model using
1 2 3 4 5 6 7 | |
Now when I run the query only those fields will show in the console as we saw earlier.
1 2 3 4 5 6 7 8 | |
In the project I’m working on I’ve created a configuration for each model so I only see what I need to see when working in the console.
There are lots more options available - refer to the Rdocs for more good stuff. I’ve found hirb really useful so encourage you to give it a go.
Related links
- Tagaholic: Hirb - Irb On The Good Stuff - Great introduction to using Hirb
- Hirb Github Repo / README - The README and Source
- Hirb RDocs - The lowdown on Hirb
- Railscast demonstrating Hirb - Ryan Bates shows hirb in action