[英]rails 4: Rails.env is different from ENV[“RAILS_ENV”]
我在config/environment.rb
文件中設置ENV["RAILS_ENV"] = "production"
以便在我的機器上運行服務器(使用rails server
)並獲得生產行為。 我的代碼中有很多行會檢查Rails.env.production?
為某些應用程序組件分配不同的功能。 我的問題是,當我在一個控制器中檢查環境時,對於Rails.env
和ENV["RAILS_ENV"]
會得到不同的結果。 第一個顯示“發展”,第二個顯示“生產”。
兩種方法都不應該返回相同的值嗎?
在評估config / environment.rb時,您只是在修改ENV哈希。 如果要在生產環境中運行應用程序,請在用於運行Rails的外殼中設置RAILS_ENV環境變量。
RAILS_ENV =生產捆綁件執行導軌c
要以生產模式運行rails服務器,請運行:
rails s -e production
並回答您的實際問題:
Rails.env
使用ENV["RAILS_ENV"]
,請參見: 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
但實際上到目前為止尚未設置ENV["RAILS_ENV"]
,因此,如果在觸發rails server命令時通過了-e,則隨選項一起顯示,請參見:
def set_environment
ENV["RAILS_ENV"] ||= options[:environment]
end
有關環境選項的信息,請參見: 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 }
而所有這些都是在執行應用程序environment.rb
之前發生的。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.