You probably spend a lot of time in IRB (or the Rails console) but have you
taken the time to customize it? Today we’ll take a look at the things I’ve
added to mine, and I’ll show you how to hack in a .irbrc_rails that’s only loaded
in the Rails console.
# ruby 1.8.7 compatiblerequire'rubygems'require'irb/completion'# interactive editor: use vim from within irbbeginrequire'interactive_editor'rescueLoadError=>errwarn"Couldn't load interactive_editor: #{err}"end# awesome printbeginrequire'awesome_print'AwesomePrint.irb!rescueLoadError=>errwarn"Couldn't load awesome_print: #{err}"end# configure irbIRB.conf[:PROMPT_MODE]=:SIMPLE# irb historyIRB.conf[:EVAL_HISTORY]=1000IRB.conf[:SAVE_HISTORY]=1000IRB.conf[:HISTORY_FILE]=File::expand_path("~/.irbhistory")# load .irbrc_rails in rails environmentsrailsrc_path=File.expand_path('~/.irbrc_rails')if(ENV['RAILS_ENV']||defined?Rails)&&File.exist?(railsrc_path)beginloadrailsrc_pathrescueExceptionwarn"Could not load: #{railsrc_path} because of #{$!.message}"endendclassObjectdefinteresting_methodscaseself.classwhenClassself.public_methods.sort-Object.public_methodswhenModuleself.public_methods.sort-Module.public_methodselseself.public_methods.sort-Object.new.public_methodsendendend
Ok! There’s not too much there, but let’s break it down from top to bottom.
Require commonly used gems
123456789101112131415161718
# ruby 1.8.7 compatiblerequire'rubygems'require'irb/completion'# interactive editor: use vim from within irbbeginrequire'interactive_editor'rescueLoadError=>errwarn"Couldn't load interactive_editor: #{err}"end# awesome printbeginrequire'awesome_print'AwesomePrint.irb!rescueLoadError=>errwarn"Couldn't load awesome_print: #{err}"end
Nothing too fancy here. Just some require commands and initialization to load up
some of my favorite and frequently used gems.
interactive_editor: Allows you to use vim (or your favorite editor) to edit
files and have them run within the context of the irb session and to edit
objects’ YAML representation.
Awesome Print: Pretty prints
Ruby objects in color and with nice formatting to show their structure.
Seriously useful if you inspect a lot of data. The .irb! call hooks it into
irb as the default formatter so you don’t even need to call it directly. It
just happens.
Prompt mode simple just makes prompts look like >> instead of
1.9.3p327 :001 >
Command history is obviously supremely useful if you frequently use the console
to hack out solutions.
Optionally load customizations for the Rails console
123456789
# load .irbrc_rails in rails environmentsrailsrc_path=File.expand_path('~/.irbrc_rails')if(ENV['RAILS_ENV']||defined?Rails)&&File.exist?(railsrc_path)beginloadrailsrc_pathrescueExceptionwarn"Could not load: #{railsrc_path} because of #{$!.message}"endend
Ahh, now things get interesting. If we detect RAILS_ENV or the Rails object is
defined then we can assume that we’re actually inside a Rails console and add
some extra configuration. We’ll get to that extra configuration for Rails in a
moment.
This one is pretty fun. It adds on a method to Object called interesting_methods.
Ruby’s object model is great, but it means that the public api to any object is full
of methods defined up its ancestor chain.
# hirb: some nice stuff for Railsbeginrequire'hirb'HIRB_LOADED=truerescueLoadErrorHIRB_LOADED=falseendrequire'logger'defloud_loggerenable_hirbset_logger_toLogger.new(STDOUT)enddefquiet_loggerdisable_hirbset_logger_tonilenddefset_logger_to(logger)ActiveRecord::Base.logger=loggerActiveRecord::Base.clear_reloadable_connections!enddefenable_hirbifHIRB_LOADEDHirb::Formatter.dynamic_config['ActiveRecord::Base']Hirb.enableelseputs"hirb is not loaded"endenddefdisable_hirbifHIRB_LOADEDHirb.disableelseputs"hirb is not loaded"endenddefefind(email)User.find_by_emailemailend# set a nice promptrails_root=File.basename(Dir.pwd)IRB.conf[:PROMPT]||={}IRB.conf[:PROMPT][:RAILS]={:PROMPT_I=>"#{rails_root}> ",# normal prompt:PROMPT_S=>"#{rails_root}* ",# prompt when continuing a string:PROMPT_C=>"#{rails_root}? ",# prompt when continuing a statement:RETURN=>"=> %s\n"# prefixes output}IRB.conf[:PROMPT_MODE]=:RAILS# turn on the loud logging by defaultIRB.conf[:IRB_RC]=Proc.new{loud_logger}
Note, for these enhancements to work in Rails apps that use bundler you’ll need to add the
required gems to your Gemfile and then run bundle.
Gemfile
12345
group :development do
gem "awesome_print"
gem "hirb"
gem "interactive_editor"
end
Hirb is an awesome thing to add to your Rails console. It
adds stuff like table formatting for models and general data, a console menu, and a pager.
The logger customizations will output things like SQL statements made to the database
unless quiet_logger is called. Very handy if you are debugging a complex ActiveRecord query.
The prompt mode configuration is just a nice prompt with the application name. We define
a :RAILS prompt mode and then use it.
That efind method is just a handy shortcut for something I do semi-often. It combines well
with a dash expander shortcut that autofills in my email address.
Want to know more?
There’s a great post on tagholic with tons of info on how to completely
customize your irb session: Exploring how to configure irb.
If you’re interested in any of the options I use in this post, odds are good
that they are explained in much more detail there.
PhishMe is Hiring!
Want to work from home with me and other awesome Rails devs to solve interesting problems for a fantastic company? A company that believes in investing back into its employees? I'm talking fully paid company trips, Ruby/Rails conferences, an expense account for Internet costs, and access to great online learning resources. Also the best coworkers ever. :-)