【问题标题】:rails 4: Rails.env is different from ENV["RAILS_ENV"]rails 4: Rails.env 不同于 ENV["RAILS_ENV"]
【发布时间】:2023-03-22 11:09:01
【问题描述】:

我在我的config/environment.rb 文件中设置ENV["RAILS_ENV"] = "production" 以便在我的机器上运行我的服务器(使用rails server)并获得生产行为。我的代码中有很多行检查Rails.env.production? 是否为某些应用程序组件分配不同的功能。 我的问题是,当我检查我的一个控制器中的环境时,Rails.envENV["RAILS_ENV"] 得到不同的结果。第一个将显示“开发”,而第二个将显示“生产”。

这两种方法不应该返回相同的值吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    在评估 config/environment.rb 时,您只是在修改 ENV 哈希。如果您想在生产环境中运行您的应用程序,请在用于运行 rails 的 shell 中设置 RAILS_ENV 环境变量。

    RAILS_ENV=生产包 exec rails c

    【讨论】:

      【解决方案2】:

      在生产模式下运行你的 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被执行之前。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-12
        • 2011-05-01
        • 1970-01-01
        • 2013-06-15
        • 2014-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多