正确的 Ruby on Rails 3 替换 ENV[“RAILS

编程入门 行业动态 更新时间:2024-10-25 06:20:39
本文介绍了正确的 Ruby on Rails 3 替换 ENV[“RAILS_ENV"] ||= 'production'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们正在升级到 Ruby on Rails 3(就像现在的半个世界),我一直在努力替换 RAILS_ENV 的用法,例如

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?

但我不确定要做什么:

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

我们在一大堆Rake任务和守护进程,其想法是您可以在命令行上传递 RAILS_ENV,但如果未通过,则默认为生产".

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.

我不确定适用于 Rails3 的新方法.所以现在我的 rails:upgrade:check 强烈抱怨 Rails2-ishness 的这种入侵......

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...

我不知道:

::Rails.env ||= 'production'

会起作用.

Rails.env 是否存在于守护进程中?

Does Rails.env exist in a daemon?

它是否会自动使用在命令行上传递的 RAILS_ENV 值进行预填充,或者我们是否需要一种调用守护进程的新方法?

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?

正确的咒语是什么?

更新:

查看 Rails.env 的源代码,

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

我们可以推断出很多事情.

we can deduce a number of things.

首先,看起来 RAILS_ENV 确实仍然存在 - 这意味着它可以被设置并且 Rails.env 会找到它...

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

如果 Rails 在守护进程的上下文中有效,那么就无需再做任何事情了.如果没有 - 那么我就可以不在乎并像以前一样使用旧的 RAILS_ENV.

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.

推荐答案

Rails.env 实际上是 ActiveSupport::StringInquirer 类型,它覆盖了 method_missing 以提供良好的相等语法.检查:api.rubyonrails/classes/ActiveSupport/StringInquirer.html

Rails.env is actually of type ActiveSupport::StringInquirer, which overrides method_missing in order to provide that nice equality syntax. Check: api.rubyonrails/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')

但是,您必须检查哪个是 Rails.env 的未初始化值,我不确定它是否真的 nil.

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

IMO,最好的做法是将 env RAILS_ENV=production 添加到所有脚本中.

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

更多推荐

正确的 Ruby on Rails 3 替换 ENV[“RAILS

本文发布于:2023-10-28 13:25:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536759.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   Ruby   Rails   ENV   RAILS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!