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.
Archived comments
Comments were previously allowed on articles. Though no new comments are being accepted you can see the old comments below.
-
Nice work. I like that a lot. Big ups to yourself and Chad.
-
FYI: I’ve updated the code above to fix a small bug with messaging
nil. -
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.
-
Sorry, I had the following at the beginning of my irbrc
IRB.conf[:LOAD_MODULES] = [] unless IRB.conf.key?(:LOAD_MODULES) -
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.)
-
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.
-
Great tip! Works like a charm.