开发者

How to set rails_env for a script or batch file

I put my batch file in lib folder and use rails db configuration, active-record like this.

require "#{File.dirname(__FILE__)}/../config/environment.rb"

class Batch
  def hello
    Message.new do |t|
      t.title = "hello"
      t.save
    end
  end
end

batch = Batch.new
batch.hello

when excute batch

ruby lib/batch.rb

in development environment it's ok

but pro开发者_JAVA百科duction environment still save development database...

how do i set rails_env batch.rb like this

ruby lib/batch.rb RAILS_ENV=production


To initialise the Rails environment, instead of putting

require "#{File.dirname(__FILE__)}/../config/environment.rb"

launch your batch file using script/runner and specify the environment with the -e option

e.g.

script/runner -e production lib/batch.rb

I think the above is The Rails Way of writing and executing a script that needs the Rails framework initialised in order to work. The alternative, as neutrino says, is to prefix the command with RAILS_ENV=value e.g.

$ RAILS_ENV=production lib/batch.rb

This is a standard shell feature to set an environment variable prior to executing a command.


Just FYI without script/runner :

RAILS_ENV=production ruby lib/batch.rb
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜