[英]Rails.env vs RAILS_ENV
I see both in examples when checking what env one is running in. What's preferred? 我在示例中看到了两个运行中的env的内容。什么是首选? Are they, for all intents and purposes equal?
出于所有意图和目的,它们是否相等?
According to the docs , #Rails.env
wraps RAILS_ENV
: 根据文档 ,
#Rails.env
包含RAILS_ENV
:
# File vendor/rails/railties/lib/initializer.rb, line 55
def env
@_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
end
But, look at specifically how it's wrapped, using ActiveSupport::StringInquirer
: 但是,使用
ActiveSupport::StringInquirer
,具体看它是如何包装的:
Wrapping a string in this class gives you a prettier way to test for equality.
在此类中包装字符串为您提供了一种更好的方法来测试相等性。 The value returned by Rails.env is wrapped in a StringInquirer object so instead of calling this:
Rails.env返回的值包含在StringInquirer对象中,因此不是调用它:
Rails.env == "production"
you can call this:
你可以这样称呼:
Rails.env.production?
So they aren't exactly equivalent, but they're fairly close. 所以它们并不完全相同 ,但它们相当接近。 I haven't used Rails much yet, but I'd say
#Rails.env
is certainly the more visually attractive option due to using StringInquirer
. 我还没有使用Rails,但是我认为
#Rails.env
肯定是因为使用StringInquirer
而具有更具视觉吸引力的选项。
Before Rails 2.x the preferred way to get the current environment was using the RAILS_ENV
constant. 在Rails 2.x之前,获取当前环境的首选方法是使用
RAILS_ENV
常量。 Likewise, you can use RAILS_DEFAULT_LOGGER
to get the current logger or RAILS_ROOT
to get the path to the root folder. 同样,您可以使用
RAILS_DEFAULT_LOGGER
获取当前记录器或RAILS_ROOT
以获取根文件夹的路径。
Starting from Rails 2.x, Rails introduced the Rails
module with some special methods: 从Rails 2.x开始,Rails为
Rails
模块引入了一些特殊方法:
This isn't just a cosmetic change. 这不仅仅是化妆品的改变。 The Rails module offers capabilities not available using the standard constants such as
StringInquirer
support. Rails模块提供了使用标准常量(如
StringInquirer
支持)所不具备的功能。 There are also some slight differences. 还有一些细微的差别。
Rails.root
doesn't return a simple String
buth a Path
instance. Rails.root
不返回简单的String
但是返回Path
实例。
Anyway, the preferred way is using the Rails
module. 无论如何,首选方法是使用
Rails
模块。 Constants are deprecated in Rails 3 and will be removed in a future release, perhaps Rails 3.1. 常量在Rails 3中已弃用,将在未来版本中删除,可能是Rails 3.1。
ENV['RAILS_ENV']
is now deprecated . ENV['RAILS_ENV']
现已弃用 。
You should use Rails.env
which is clearly much nicer. 你应该使用
Rails.env
,这显然更好。
Strange behaviour while debugging my app: require "active_support/notifications" (rdb:1) p ENV['RAILS_ENV'] "test" (rdb:1) p Rails.env "development" 调试我的应用程序时出现奇怪的行为:需要“active_support / notifications”(rdb:1)p ENV ['RAILS_ENV']“test”(rdb:1)p Rails.env“development”
I would say that you should stick to one or another (and preferably Rails.env) 我会说你应该坚持一个或另一个(最好是Rails.env)
更新:在Rails 3.0.9中:在railties / lib / rails.rb中定义的env方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.