For modern Rails versions (3+), Rails.env
returns the environment as a String
:
Rails.env #=> "production"
There are also helpful accessors* for each environment that will return a Boolean
:
Rails.env.production? #=> true
Rails.env.staging? #=> false
Rails.env.development? #=> false
(*) There's a gotcha here: these aren't real accessors. They're just strings of letters and if they happen to match the current environment name, they return true. They fail silently. That means that you can be in production, but if have a typo in this code, you won't get an error, you'll simply get false
:
Rails.env.producton? #=> false
For that reason, I set constants in an initializer and only refer to those in the rest of my code. This lets the Ruby interpreter help me catch my own errors:
PRODUCTION = Rails.env.production?
DEVELOPMENT = Rails.env.development?
TEST = Rails.env.test?