Rails.env vs RAILS_ENV

Ruby on-Rails

Ruby on-Rails Problem Overview


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

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

ENV['RAILS_ENV'] is now deprecated.

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

Solution 3 - Ruby on-Rails

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.

Solution 4 - Ruby on-Rails

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)

Solution 5 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbradView Question on Stackoverflow
Solution 1 - Ruby on-RailsMark RushakoffView Answer on Stackoverflow
Solution 2 - Ruby on-RailssuperluminaryView Answer on Stackoverflow
Solution 3 - Ruby on-RailsSimone CarlettiView Answer on Stackoverflow
Solution 4 - Ruby on-RailsJuYoView Answer on Stackoverflow
Solution 5 - Ruby on-RailsjgpawletkoView Answer on Stackoverflow