Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Ruby on Rails 3 replacement for ENV["RAILS_ENV"] ||= 'production'?

We're doing an upgrade to Ruby on Rails 3 (like half the world right now), and I've been diligently replacing usages of RAILS_ENV, for example

RAILS_ENV == 'wibble'
# becomes
Rails.env.wibble?

But I'm not as certain of what to do with:

ENV["RAILS_ENV"] ||= 'production'

We've got it at the top of a whole bunch of Rake tasks and daemons, and the idea is that you can pass RAILS_ENV on the command-line, but it defaults to 'production' if it's not passed.

I'm not sure of the new Rails3-appropriate way of doing this. So for now my rails:upgrade:check is complaining mightily of this intrusion of Rails2-ishness...

I don't know if:

::Rails.env ||= 'production'

will work.

Does Rails.env exist in a daemon?

Does it automagickally get pre-populated with the value of RAILS_ENV passed on the command-line or do we need a new way of invoking the daemons?

What is the correct mantra for this?


Update:

Looking into the source-code for Rails.env,

def env
  @_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
end

we can deduce a number of things.

Firstly, it looks like RAILS_ENV does actually still exist - which means it can be set and Rails.env will find it...

If Rails is valid in the context of a daemon, then nothing more needs to be done. If not - then I could just not care much and use the old RAILS_ENV as before.

like image 952
Taryn East Avatar asked Oct 25 '10 17:10

Taryn East


3 Answers

Rails.env is actually of type ActiveSupport::StringInquirer, which overrides method_missing in order to provide that nice equality syntax. Check: http://api.rubyonrails.org/classes/ActiveSupport/StringInquirer.html

So, if you want to override it to be "production" by defaut, you should write:

Rails.env ||= ActiveSupport::StringInquirer.new('production')

However, you'll have to check which is the uninitialized value of Rails.env, I'm not sure it's really nil.

The best course of action, IMO, is to just prepend env RAILS_ENV=production to all your scripts.

like image 143
Fábio Batista Avatar answered Nov 08 '22 16:11

Fábio Batista


Edit lib/tasks/environments.rake

# Sets environments as needed for rake tasks
%w[development production staging].each do |env|
  desc "Runs the following task in the #{env} environment" 
  task env do
    Rails.env = env
  end
end

task :testing do
  Rake::Task["test"].invoke
end

task :dev do
  Rake::Task["development"].invoke
end

task :prod do
  Rake::Task["production"].invoke
end

Source

UPDATE

pass RAILS_ENV=production via command line, something like this:

RAILS_ENV=production rake db:setup

Does this help:

# before
if RAILS_ENV == 'production'
  ...

# Rails 3
if Rails.env.production?
like image 9
zengr Avatar answered Nov 08 '22 18:11

zengr


if Rails.env.production?
  puts '...'
like image 2
Quanyi Ma Avatar answered Nov 08 '22 17:11

Quanyi Ma