Have a custom .irbrc for a Rails 3 project

If you are Rails console hacker like tisba and me you maybe find this really useful:

Today tisba had the problem of performing the same piece of code each time he runs rails console. Obviously this would be done in the ~/.irbrc. But wait! If that code in question would be project specific, which it eventually was, it would break every attempt to start an IRB session outside of that project. So we asked ourselves: "Wouldn't it be great to have a project specific .irbrc" - Yeah, it would!

Thanks to Rails great API it took me only a few minutes (actually less then writing up with this blog post ...) to came up with this simple method:

# File: config/application.rb
require File.expand_path('../boot', __FILE__)

require 'rails/all'

# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env) if defined?(Bundler)

module MyApp
  class Application < Rails::Application
    # config stuff comes here

    def load_console(sandbox=false)
      super
      if File.exists?(project_specific_irbrc = File.join(Rails.root, ".irbrc"))
        puts "Loading project specific .irbrc ..."
        load(project_specific_irbrc)
      end
    end

  end
end

Just add it to your MyApp::Application class (the one defined in config/application.rb) and add your very own custom .irbrc in your Rails root directory.

Update: tisba mentioned it would be nice if the "Loading" line would be only printed if the file actually exists. I'm sure you gonna agree on that too. What you see now is the updated version of that snippet.

See you Space Cowboy ...
blog comments powered by Disqus
 
Fork me on GitHub