繁体   English   中英

rails 4:Rails.env与ENV [“ RAILS_ENV”]不同

[英]rails 4: Rails.env is different from ENV[“RAILS_ENV”]

我在config/environment.rb文件中设置ENV["RAILS_ENV"] = "production"以便在我的机器上运行服务器(使用rails server )并获得生产行为。 我的代码中有很多行会检查Rails.env.production? 为某些应用程序组件分配不同的功能。 我的问题是,当我在一个控制器中检查环境时,对于Rails.envENV["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,则随选项一起显示,请参见:

https://github.com/rails/rails/blob/3e36db4406beea32772b1db1e9a16cc1e8aea14c/railties/lib/rails/commands/server.rb#L62-64

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM