Rails.env vs RAILS_ENV

前端 未结 5 998
难免孤独
难免孤独 2020-11-30 17:38

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条回答
  • 2020-11-30 18:23

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

    0 讨论(0)
  • 2020-11-30 18:28

    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.

    0 讨论(0)
  • 2020-11-30 18:39

    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.

    0 讨论(0)
  • 2020-11-30 18:40

    ENV['RAILS_ENV'] is now deprecated.

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

    0 讨论(0)
  • 2020-11-30 18:44

    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)

    0 讨论(0)
提交回复
热议问题