Rails 7.1 introduced a new method Rails.env.local?
which returns true if the environment is development
or test
.
This is useful when we want to run some code only in development or test environment.
Before
In Rails Applications, we have many code paths that want to run only in development or test environment.
We maybe have many different enviroments like development
, test
, staging
, production
etc.
Or multiple staging and review applications.
In such cases, we have to check for the environment name in the code. For example:
unless Rails.env.development? || Rails.env.test?
# call some external API
ExternalAPI.call
end
or
if Rails.env.development? || Rails.env.test?
# create some test data for development or test environment
end
After
With the introduction of Rails.env.local?
, we can now write the above code as:
unless Rails.env.local?
# call some external API
ExternalAPI.call
end
or
if Rails.env.local?
# create some test data for development or test environment
end
IRB and Rails Console auto-completion
Rails 7.1 also introduced a feature to disable auto-completion in Rails console by default on production.
This is useful when we are working with a large Rails application and the auto-completion is slow especially when connecting remotely to the console.
Previously, this auto-completion was disabled with Rails.env.production?
check to not run only in production.
But that meant it was still enabled and made things slower or introduced issues with auto-completion in staging or other environments.
With this change, auto-completion is disabled by default,
only if the environment is development
or test
, leveraging the new Rails.env.local?
method.
Summary
Rails.env.local?
shorthands the check for Rails.env.development? || Rails.env.test?
and is useful when we want to run some code only in development or test environment.