Loading additional files when starting script/console

I use the Rails console quite a lot, and from a co-worker I had received a .irbrc file that contains a method called ‘log_to’ which enables on-screen query logging in the Rails console. It still required me to call this method every time I started the console though, because even though it’s defined in .irbrc, it cannot be executed from there since it uses Rails specific code (which is not loaded at the time that the .irbrc is loaded.

So, naturally I was wondering whether it is possible to auto-execute any commands while starting script/console. It turns out it isn’t (according to the friendly people on IRC). With the help of madnificent though, I can now do it. He made a small change to rails/railties/lib/commands/console.rb, which will change the behaviour of the console such that it will look in #{RAILS_ROOT}/console_scripts for any additional Ruby files to load.

Please note, for this to work you will need to either freeze rails in your vendor directory, or change your local rails source. As I’m very new to Rails I’m not sure why this kind of functionality is not already in (or perhaps it is but I just could not find it), but I’m hoping it will be picked up somehow ;)

I have also included the script I wanted to load in the first place, I find it quite handy to be able to see what kind of queries my commands are generating.

You can find the files on Pastie and on my webserver (console.rb and enable_sql_logging.rb).

Advertisements

One Response to Loading additional files when starting script/console

  1. madnificent says:

    Straightforward blogpost. I like this!

    /me bookmarks this blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: