toolmantim

System-wide script/console logging

February 06, 2007 16:24 (Sydney Australia), updated about 17 hours later

Last time I mentioned the environment.rb logger hack that helps understand Rails activity in script/console. The only problem was you had to add it to each Rails app’s environment.rb.

Thanks to a hint left by Chad Humpries we now have it system-wide via your .irbrc file.

Chuck the following in your ~/.irbrc file, load up a console and try a User.find(:first).

Update: I’ve slightly rewritten Chad’s code below to prevent a NoMethodError on nil, remove some unnecessary parenthesises and to use && instead of and.


script_console_running = ENV.include?('RAILS_ENV') && IRB.conf[:LOAD_MODULES] && IRB.conf[:LOAD_MODULES].include?('console_with_helpers')
rails_running = ENV.include?('RAILS_ENV') && !(IRB.conf[:LOAD_MODULES] && IRB.conf[:LOAD_MODULES].include?('console_with_helpers'))
irb_standalone_running = !script_console_running && !rails_running

if script_console_running
  require 'logger'
  Object.const_set(:RAILS_DEFAULT_LOGGER, Logger.new(STDOUT))
end

Look ma… inline logging:


$ ./script/console 
Loading development environment.
>> Person.find(:first)
  Person Load (0.000432)   SELECT * FROM people LIMIT 1
=> #<Person:0x139a2c8 @attributes={...}>

How dandy.

Comments

Dan Webb

Nice work. I like that a lot. Big ups to yourself and Chad.

Tim Lucas

FYI : I’ve updated the code above to fix a small bug with messaging nil.

Lindsay Evans

Neato.

Although now I’ll have to mess with script/console to get ANSI colours working properly :(

BTW , Windows users will need to put .irbrc in their user profile directory (C:\Documents and Settings\[username]), then set the HOME env var to that directory.

Chad Humphries

Sorry, I had the following at the beginning of my irbrc


IRB.conf[:LOAD_MODULES] = []  unless IRB.conf.key?(:LOAD_MODULES)

MAX HENSCHEL

TO:> System-wide script/console logging-

It was a “NICE” try (?!!—)

I do believe that programmers can (yes: can…) do a lot better. Small white print on pitch black (??) background makes for hard-to read TEXT !!— THANK YOU VERY MUCH DEAR Fellos.—

Houston, Texas (LONE STAR STATE .)

Nate Klaiber

Thanks for this tip. I was previously using Jamis Buck’s tip of adding to environemnt.rb, but this makes things much nicer as I want to have it available across all apps.

Marcus

Great tip! Works like a charm.

To comment on this article you must have javascript enabled.