I set in my config/environment.rb
file ENV["RAILS_ENV"] = "production"
in order to run my server on my machine (using rails server
) and get the production behavior. I have a lot of lines in my code that check if Rails.env.production?
to assign a different functionality for some of the app components. My problem is that when I check the environment in one of my controller I get different results for Rails.env
and ENV["RAILS_ENV"]
. The first will show "development" while the second will be "production".
Shouldn't both of the methods return the same value?
By the time config/environment.rb is evaluated you're just modifying the ENV hash. If you want to run your app in production set the RAILS_ENV environment variable in the shell you use to run rails.
RAILS_ENV=production bundle exec rails c
To run your rails server in production mode run :
rails s -e production
And to answer your actual question :
Rails.env
uses ENV["RAILS_ENV"]
internally, see : https://github.com/rails/rails/blob/d25fe31c40928712b5e08fe0afb567c3bc88eddf/railties/lib/rails.rb#L59-L61
def env
@_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
end
but ENV["RAILS_ENV"]
which is actually not set till now, so the option that is passed with -e if passed while the rails server command is triggered comes into picture, see:
def set_environment
ENV["RAILS_ENV"] ||= options[:environment]
end
for environment option see: https://github.com/rails/rails/blob/3e36db4406beea32772b1db1e9a16cc1e8aea14c/railties/lib/rails/commands/server.rb#L31
opts.on("-e", "--environment=name", String,
"Specifies the environment to run this server under (test/development/production).",
"Default: development") { |v| options[:environment] = v }
and all this is happening before your applications environment.rb
is executed.
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.