13 Rails-specific hints for your rails 3 console.

.railsrc – how to load it?

The .railsrc file should only be loaded in Rails enviroments. Put the following snippet into your ~/.irbrc or use the lastest irbtools:

load_railsrc 1 2 3 4 5 6 7 8 railsrc_path = File . expand_path (' ~/.railsrc ') if ( ENV [' RAILS_ENV '] || defined? Rails ) && File . exist? ( railsrc_path ) begin load railsrc_path rescue Exception warn " Could not load: #{ railsrc_path } " end end

ActiveRecord’s SQL queries

This one is the most common (and helpful) rails console tweak. It shows the SQL queries Rails is doing:

active_record_logger 1 2 ActiveRecord :: Base . logger = Logger . new STDOUT ActiveRecord :: Base . clear_reloadable_connections!

ActionController logger

The ActionController logger functions in the same way like the ActiveRecord logger above: It displays its actions within the console:

action_controller_logger 1 ActionController :: Base . logger = Logger . new STDOUT

By the way, You can do controller requests using the app object.

Named routes

You can access your app’s named route urls in from the console:

named_routes 1 2 include Rails . application . routes . url_helpers default_url_options [ :host ] = Rails . application . class . parent_name . downcase

ActionView helpers

You can use ActionView’s (including your own) helpers using the helper object. You can even include them directly to your global console namespace.

action_view_helpers 1 2 3 4 5 6 7 8 9 10 11 12 13 include ApplicationController . _helpers include ActionView :: Helpers :: DebugHelper include ActionView :: Helpers :: NumberHelper include ActionView :: Helpers :: RawOutputHelper include ActionView :: Helpers :: SanitizeHelper include ActionView :: Helpers :: TagHelper include ActionView :: Helpers :: TextHelper include ActionView :: Helpers :: TranslationHelper

Some nice route table views

Get table views for your routes (requires hirb):

route_tables 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 class Hirb::Helpers::Route < Hirb :: Helpers :: AutoTable def self.render ( output , options = {}) super ( output . requirements . map { | k , v | [ k , v . inspect ] }, options . merge ({ :headers => [ output . name || ' ', " #{ output.verb || 'ANY' } #{ output.path } "], :unicode => true , :description => nil , }) ) end end Hirb . add_view ActionDispatch :: Routing :: Route , :class => Hirb :: Helpers :: Route def routes ( long_output = false ) if long_output Rails . application . routes . routes . each { | e | puts Hirb :: Helpers :: Route . render ( e ) } true else Hirb :: Console . render_output Rails . application . routes . routes . map {| e | [ e . name || ' ', e . verb || ' ANY ', e . path ] },{ :class => Hirb :: Helpers :: AutoTable , :headers => %w< name verb path >, } end end def route ( index_or_name ) route = case index_or_name when Integer Rails . application . routes . routes [ index_or_name ] when Symbol Rails . application . routes . named_routes . get index_or_name end end def r ActionController :: Routing :: Routes end

Rails prompt

Isn’t it nice to see the current project+environment in your prompt: rails_app(dev)> ? You need to add this:

ripl version:

rails_prompt_ripl 1 2 3 4 5 6 7 module Ripl::RailsPrompt def prompt @prompt = " #{ Rails.application.class.parent_name.downcase } ( #{ Rails.env[0...3] } )> " super end end Ripl :: Shell . include Ripl :: RailsPrompt

irb version:

rails_prompt_irb 1 2 3 4 5 6 7 8 9 10 11 12 app_name = Rails . application . class . parent_name . downcase app_env = Rails . env [ 0 ... 3 ] IRB . conf [ :PROMPT ] ||= {} IRB . conf [ :PROMPT ][ :RAILS ] = { :PROMPT_I => " #{ app_name } ( #{ app_env } )> ", :PROMPT_N => " #{ app_name } ( #{ app_env } )| ", :PROMPT_C => " #{ app_name } ( #{ app_env } )| ", :PROMPT_S => " #{ app_name } ( #{ app_env } )%l ", :RETURN => " => %s

", :AUTO_INDENT => true , } IRB . conf [ :PROMPT_MODE ] = :RAILS

Per project histories

I also like to have a unique console history for each of my rails projects (in a .console_history file):

ripl version:

rails_history_ripl 1 Ripl . config [ :history ] = File . join Dir . pwd , ' .console_history '

irb version:

rails_history_irb 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 history_file = File . join Dir . pwd , ' .console_history ' if ! IRB . conf [ :PROMPT ][ :RVM ] IRB . conf [ :HISTORY_FILE ] = history_file else if File . exists? ( history_file ) lines = IO . readlines ( history_file ). collect { | line | line . chomp } Readline :: HISTORY . clear Readline :: HISTORY . push (* lines ) end Kernel :: at_exit do maxhistsize = IRB . conf [ :SAVE_HISTORY ] || 100 history_file = File . join Dir . pwd , " .console_history " lines = Readline :: HISTORY . to_a . reverse . uniq . reverse lines = lines [- maxhistsize , maxhistsize ] if lines . compact . length > maxhistsize File :: open ( history_file , " w+ ") { | io | io . puts lines . join ("

") } end end

SQL helper method

Plain SQL:

sql 1 2 3 def sql ( query ) ActiveRecord :: Base . connection . select_all ( query ) end

Model#find helper methods

Instead of User.find.. you can do user.. . Without arguments it only returns the model class. Based on this snippet.

model_find 1 2 3 4 5 6 7 8 9 10 11 12 13 Dir . glob ( File . join ( Dir . pwd , *%w< app models ** *.rb >) ). map { | file_name | table_name = File . basename ( file_name ). split (' . ')[ 0 ..- 2 ]. join Object . instance_eval do define_method ( table_name ) do |* args | table_class = table_name . camelize . constantize if args . empty? table_class else table_class . send ( :find , * args ) end end end }

Edit records with vim

console_update is similar to interactive_editor, but offers more options:

Misc DB helper methods

I bundle them in a db object:

ar_shortcuts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 module DatabaseHelpers extend self def tables Hirb :: Console . render_output ActiveRecord :: Base . connection . tables . map {| e |[ e ]},{ :class => Hirb :: Helpers :: AutoTable , :headers => %w< tables >, } true end def table ( which ) Hirb :: Console . render_output ActiveRecord :: Base . connection . columns ( which ). map { | e | [ e . name , e . type , e . sql_type , e . limit , e . default , e . scale , e . precision , e . primary , e . null ] },{ :class => Hirb :: Helpers :: AutoTable , :headers => %w< name type sql_type limit default scale precision primary null >, } true end def counts Hirb :: Console . render_output ActiveRecord :: Base . connection . tables . map {| e | [ e , ActiveRecord :: Base . connection . select_value (" SELECT COUNT(*) FROM #{e} ")] },{ :class => Hirb :: Helpers :: AutoTable , :headers => %w< table count >, } true end end def db ; DatabaseHelpers ; end

Authlogic

Initialize Session:

init_authlogic 1 2 3 4 if defined? Authlogic Authlogic :: Session :: Base . controller = Authlogic :: ControllerAdapters :: RailsAdapter . new ( self ) end

Putting it all together

gist

Have another nice helper? Post it in the comments ;)