How to set rails_env for script or batch file

I put my batch file in the lib folder and use the rails db configuration, an active entry 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 package exute

 ruby lib/batch.rb 

in a development environment this is normal

but the production environment still retains the development database ...

how to set rails_env batch.rb like this

 ruby lib/batch.rb RAILS_ENV=production 
+4
source share
2 answers

To initialize a Rails environment instead of hosting

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

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

eg.

 script/runner -e production lib/batch.rb 

I think the Rails method described above is for writing and executing a script that requires a Rails infrastructure initialized to work. An alternative, like neutrino , is a command prefix with RAILS_ENV = value, for example.

 $ RAILS_ENV=production lib/batch.rb 

This is a standard shell function for setting an environment variable before executing a command.

+5
source

Just FYI without script / runner:

 RAILS_ENV=production ruby lib/batch.rb 
+2
source

Source: https://habr.com/ru/post/1300660/


All Articles