Console Snacks[摘自Advanced Rails Recipes]

1. Write Console Methods

在~/.irbrc定义ActvieRecord::Base.connection.select_all方法

1.# ~/.railsrc
2.def sql(query)
3.ActiveRecord::Base.connection.select_all(query)
4.end
1.# ~/.irbrc
2.if ENV['RAILS_ENV']
3.load File.dirname(__FILE__) + '/.railsrc'
4.end

这样就可以在直接在script/console下面执行sql查询

1.$ script/console
2.>> sql 'show databases'

2. Log to the console

ActiveRecord Logger

01.# ~/.railsrc
02.def loud_logger
03.set_logger_to Logger.new(STDOUT)
04.end
05. 
06.def quiet_logger
07.set_logger_to nil
08.end
09. 
10.def set_logger_to(logger)
11.ActiveRecord::Base.logger = logger
12.ActiveRecord::Base.clear_active_connections!
13.end

ActionPack Logger

1.# ~/.railsrc
2.require 'logger'
3.Object.const_set(:RAILS_DEFAULT_LOGGER, Logger.new(STDOUT))

3. Play in the Sandbox

使用sandbox参数来启动script/console

1.script/console --sandbox

这样所有的数据库修改都会在退出console时被恢复

4. Access Helpers

直接调用helper方法

1.helper.pluralize(3'blind mouse')

调用自定义的helper方法

1.helper.extends BlogsHelper
2.helper.archive_dates
posted @ 2010-08-05 18:11  麦飞  阅读(225)  评论(1编辑  收藏  举报