Skip to content

Commit 47eaf88

Browse files
authored
Add Rails.env.local? (rails#46786)
* Add Rails.env.local? So many checks against Rails.env is whether we're running test or development, so combine into just one. * Add CHANGELOG * Prevent 'local' from being used as an environment name Now that we have it as a combined predicate for dev + test.
1 parent 2e142d9 commit 47eaf88

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

activesupport/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Add `Rails.env.local?` shorthand for `Rails.env.development? || Rails.env.test?`.
2+
3+
*DHH*
4+
15
* `ActiveSupport::Testing::TimeHelpers` now accepts named `with_usec` argument
26
to `freeze_time`, `travel`, and `travel_to` methods. Passing true prevents
37
truncating the destination time with `change(usec: 0)`.

activesupport/lib/active_support/environment_inquirer.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
# frozen_string_literal: true
22

33
require "active_support/string_inquirer"
4+
require "active_support/core_ext/object/inclusion"
45

56
module ActiveSupport
67
class EnvironmentInquirer < StringInquirer # :nodoc:
78
# Optimization for the three default environments, so this inquirer doesn't need to rely on
89
# the slower delegation through method_missing that StringInquirer would normally entail.
910
DEFAULT_ENVIRONMENTS = %w[ development test production ]
11+
12+
# Environments that'll respond true for #local?
13+
LOCAL_ENVIRONMENTS = %w[ development test ]
14+
1015
def initialize(env)
16+
raise(ArgumentError, "'local' is a reserved environment name") if env == "local"
17+
1118
super(env)
1219

1320
DEFAULT_ENVIRONMENTS.each do |default|
@@ -18,5 +25,10 @@ def initialize(env)
1825
DEFAULT_ENVIRONMENTS.each do |env|
1926
class_eval "def #{env}?; @#{env}; end"
2027
end
28+
29+
# Returns true if we're in the development or test environment.
30+
def local?
31+
in? LOCAL_ENVIRONMENTS
32+
end
2133
end
2234
end
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "abstract_unit"
4+
5+
class EnvironmentInquirerTest < ActiveSupport::TestCase
6+
test "local predicate" do
7+
assert ActiveSupport::EnvironmentInquirer.new("development").local?
8+
assert ActiveSupport::EnvironmentInquirer.new("test").local?
9+
assert_not ActiveSupport::EnvironmentInquirer.new("production").local?
10+
end
11+
12+
test "prevent local from being used as an actual environment name" do
13+
assert_raises(ArgumentError) do
14+
ActiveSupport::EnvironmentInquirer.new("local")
15+
end
16+
end
17+
end

0 commit comments

Comments
 (0)