227

I see both in examples when checking what env one is running in. What's preferred? Are they, for all intents and purposes equal?

5 Answers 5

387

According to the docs, #Rails.env wraps 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:

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

Sign up to request clarification or add additional context in comments.

5 Comments

nice explanation, thx! I'm also trying to find where RAILS_ENV is defined? Any idea??
It's worth mentioning that Rails.env is the new standard as RAILS_ENV is being deprecated.
Ryan, on a command line, you can't use Rails.env. so if it's deprecating soon, then what would you use on the CLI?
Using Rails.env.production? secures you against typos actually changing the environment like this: RAILS_ENV = "production". Notice the missed = sign.
All this ridiculous complexity just so you can use a question mark?
36

ENV['RAILS_ENV'] is now deprecated.

You should use Rails.env which is clearly much nicer.

Comments

29

Before Rails 2.x the preferred way to get the current environment was using the RAILS_ENV constant. Likewise, you can use RAILS_DEFAULT_LOGGER to get the current logger or RAILS_ROOT to get the path to the root folder.

Starting from Rails 2.x, Rails introduced the Rails module with some special methods:

  • Rails.root
  • Rails.env
  • Rails.logger

This isn't just a cosmetic change. The Rails module offers capabilities not available using the standard constants such as StringInquirer support. There are also some slight differences. Rails.root doesn't return a simple String buth a Path instance.

Anyway, the preferred way is using the Rails module. Constants are deprecated in Rails 3 and will be removed in a future release, perhaps Rails 3.1.

2 Comments

FYI, from what was discussed here, it sounds like those methods were introduced in Rails 2.3, not 2.0.
We're using 2.1.2 on a project. Rails.env works without a problem.
2

Strange behaviour while debugging my app: require "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)

Comments

2

Update: in Rails 3.0.9: env method defined in railties/lib/rails.rb

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.