2012年6月29日

Run Ruby Script in Rails Environment

Overview

If you wanna execute some ruby code in rails environment, say manipulate w/ model or something, you can always try rake task first. But there're circumstances you don't want to use it, maybe it's just a one-time script that you don't want to save it to git, or whatever.

I've found out there're two simple ways to accomplish it.

require config/environment.rb

# test.rb
require "config/environment"
p User.first

# in terminal
ruby test.rb

use rails runner

Rails Guides about rails runner

runner runs Ruby code in the context of Rails non-interactively. For instance:

rails runner "p User.first"
rails runner some_ruby_script.rb
rails runner -e staging "Model.long_running_method"
rails runner -h

You can also use the alias “r” to invoke the runner: rails r.

I failed to call rails r on Rails 3.0.10, maybe it's above 3.1+.

Share on Twitter Share the post
Qihuan Piao

风七

笔名兼游戏内常用名"风七",标准宅男,长居东京。喜好有常、不善言谈,但在这个博客小窝里却是尽其能的大肆抒发阴晴圆缺。喜欢一成不变的生活。

还有用英语日语写东西,有兴趣的话不妨看看:)