# Understanding How Rails Environments Work

*Published on January 24, 2024*

Tags: Rails Internals

---


Rails applications typically run in one of three environments:&nbsp;`development`,&nbsp;`test`, and&nbsp;`production`. In addition, you can create your own custom environment, such as&nbsp;`qa`&nbsp;or&nbsp;`staging`.

Each of these environments has its own configuration settings, which allows your application to behave differently based on the environment it’s running in. For example, your app can log to standard output in development, whereas it might use an external logging service in production.

**How does Rails know which environment to use?**

To figure out the current environment, Rails uses the&nbsp;`RAILS_ENV`&nbsp;environment variables. If that’s not set, it will use the&nbsp;`RACK_ENV`&nbsp;variable. You can set&nbsp;`RAILS_ENV`&nbsp;to one of the following values to choose the correct environment:&nbsp;`development`&nbsp;`test`, or&nbsp;`production`.

To set the Rails environment, you’d use the following command in a terminal (or in a&nbsp;`.bashrc`&nbsp;or&nbsp;`.zshrc`&nbsp;file)

```bash
$ export RAILS_ENV=production
```

Alternatively, you can specify the environment name by passing the&nbsp;`-e`&nbsp;flag to Rails commands.

```bash
$ bin/rails server -e staging
```

You can also set the environment in your Ruby code. In fact, that’s what the default&nbsp;`test_helper`&nbsp;does in a Rails application.

```ruby
# test/test_helper.rb

ENV["RAILS_ENV"] ||= "test"
```

**Note:**&nbsp;If you don’t set any of the above environment variables, Rails will assume the&nbsp;`development`&nbsp;environment as a default.

For each of the above environments, Rails provides a dedicated configuration file stored under the&nbsp;`config/environments`&nbsp;directory. If you open a newly minted Rails application, you will notice three files in there:&nbsp;`development.rb`,&nbsp;`test.rb`, and&nbsp;`production.rb`, containing the configuration settings for each environment.

Put the configuration settings common to all environments in the&nbsp;`config/application.rb`&nbsp;file, and settings specific to a particular environment in the&nbsp;`config/environments/#{env}.rb`&nbsp;file.

> 💡Environment config files take precedence over the application config.

### **🤔 Which environment I'm using?**

To figure out the current environment your application is running under, use the&nbsp;`Rails.env`&nbsp;method, which returns a string containing the name of the environment.

```ruby
Rails.env  # "development"
```

Alternatively, you can use the query methods named after the environments.

```ruby
Rails.env.production?  # false
Rails.env.test?        # true
```

To create and configure a new environment, say “staging”, you’d simply add a new `config/environments/staging.rb`&nbsp;file with its own settings. This new environment is no different than other. You can start a server with&nbsp;`bin/rails server -e staging`, launch a console with&nbsp;`bin/rails console -e staging`, and check the environment using&nbsp;`Rails.env.staging?`&nbsp;method.

**But you probably knew all of that.**&nbsp;So let’s learn something new and interesting by taking a peek behind the scenes to understand how it's implemented.

## Behind the Scenes of Rails Environments

The&nbsp;`env`&nbsp;method is defined in the&nbsp;`railties/lib/rails.rb`&nbsp;file. It returns the current Rails environment. Here’s the implementation:

```ruby
# railties/lib/rails.rb

module Rails
  class << self
    def env
      @_env ||= ActiveSupport::EnvironmentInquirer.new(
        ENV["RAILS_ENV"].presence || 
        ENV["RACK_ENV"].presence || 
        "development"
      )
    end
  end
end
```

As you can see, Rails lazily sets the value of the&nbsp;`@_env`&nbsp;variable to an instance of the `EnvironmentInquirer`&nbsp;class, passing the values of&nbsp;`RAILS_ENV`,&nbsp;`RACK_ENV`, and&nbsp;`"development"`&nbsp;in that order.

The&nbsp;`EnvironmentInquirer`&nbsp;class takes the name of the environment, i.e.&nbsp;`"production"`,&nbsp;`"test"`, or&nbsp;`"development"`&nbsp;and does two things:

1. Set the corresponding instance variable to&nbsp;`true`&nbsp;or&nbsp;`false`&nbsp;if it matches the passed environment name.
2. Add query methods like&nbsp;`test?`&nbsp;or&nbsp;`production?`&nbsp;returning the above value. This allows you to query the environment like&nbsp;`Rails.env.development?`&nbsp;and so on.

Here’s the simplified source code.

```ruby
# activesupport/lib/active_support/environment_inquirer.rb

module ActiveSupport
  class EnvironmentInquirer < StringInquirer
    DEFAULT_ENVIRONMENTS = %w[ development test production ]

    def initialize(env)
      DEFAULT_ENVIRONMENTS.each do |default|
        instance_variable_set :"@#{default}", env == default
      end
      @local = in? LOCAL_ENVIRONMENTS
    end

    DEFAULT_ENVIRONMENTS.each do |env|
      class_eval <<~RUBY, __FILE__, __LINE__ + 1
        def #{env}?
          @#{env}
        end
      RUBY
    end
  end
end
```

In addition, it also adds a&nbsp;`local?`&nbsp;query method that returns&nbsp;`true`&nbsp;if the current environment is&nbsp;`development`&nbsp;or&nbsp;`test`. This is a handy shortcut if you want to skip running some code in production, or run something only in production.

**Note:**&nbsp;If you don't know how&nbsp;`class_eval`&nbsp;works in Ruby, I highly recommend reading Paolo Perrotta's [Metaprogramming Ruby 2](/metaprogramming-ruby).

## **What is a String Inquirer?**

You must have noticed that the&nbsp;`EnvironmentInquirer`&nbsp;class inherits from the&nbsp;`StingInquirer`&nbsp;class. What’s going on?

The&nbsp;`StringInquirer`&nbsp;class provides a query- based way to compare two strings. Here’s a simple example:

```ruby
def result
  ActiveSupport::StringInquirer.new("success")
end

result.success?   # true
env.failure?      # false
```

This lets you query the&nbsp;`env`&nbsp;method against any other environment name, such as `Rails.env.staging?`&nbsp;or&nbsp;`Rails.env.qa?`.

In fact, we didn’t even have to define the&nbsp;`DEFAULT_ENVIRONMENTS`&nbsp;constant above and `EnvironmentInquirer`&nbsp;would have handled the default environments. It’s an optimization for the three default environments, so this inquirer doesn't need to rely on the slower delegation through&nbsp;`method_missing`&nbsp;that&nbsp;`StringInquirer`&nbsp;would normally use.

To learn more about string and array inquries, check out the following post:

- [Compare Strings Using Inquiry](/compare-strings-using-string-inquiry)
- [Array Inquiry in Rails](/array-inquirer-in-rails)

## **Override Existing Configuration**

Sometimes, you may want to create a new configuration that mimics existing configuration, with only one or two settings being different. For example, the staging environment typically matches the production environment, with only difference being the database connection.

In these cases, you can require the existing configuration and override it in-place as follows.

```ruby
# config/environments/staging.rb
require_relative "production"

Rails.application.configure do
  # config settings specific to
  # the staging environment.
end
```

**Bonus: Did you know about the**&nbsp;`bin/rails about`&nbsp;**command?**

```bash
$ bin/rails about

About your application's environment
Rails version             7.1.2
Ruby version              ruby 3.2.3 (2024-01-18 revision 52bb2ac0a6) [x86_64-darwin21]
RubyGems version          3.4.19
Rack version              3.0.8
Middleware                ActionDispatch::HostAuthorization, Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, ActionDispatch::ServerTiming, ...
Application root          /Users/akshay/blog
Environment               development
Database adapter          sqlite3
Database schema version   20240111083326
```

You're welcome 😉

### Further Reading

1. Check out all the available settings for various Rails sub-frameworks on the official Rails Guides on&nbsp;[Configuring Rails Applications](https://guides.rubyonrails.org/configuring.html).
2. This article covers some of the important configuration settings that are common to most Rails applications:&nbsp;[Configuring Rails Environments](/configuring-rails-environments)
3. For an interesting read on how Basecamp used Rails environments other than the default ones, check out this article&nbsp;[Beyond the default Rails environments](https://signalvnoise.com/posts/3535-beyond-the-default-rails-environments)&nbsp;from David. It’s over a decade old, but interesting nonetheless.

