Class: RuboCop::Cop::Rails::EnvLocal

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector, TargetRailsVersion
Defined in:
lib/rubocop/cop/rails/env_local.rb

Overview

Checks for usage of ‘Rails.env.development? || Rails.env.test?` which can be replaced with `Rails.env.local?`, introduced in Rails 7.1.

Examples:


# bad
Rails.env.development? || Rails.env.test?

# good
Rails.env.local?

Constant Summary collapse

MSG =
'Use `Rails.env.local?` instead.'
MSG_NEGATED =
'Use `!Rails.env.local?` instead.'
LOCAL_ENVIRONMENTS =
%i[development? test?].to_set.freeze

Constants included from TargetRailsVersion

TargetRailsVersion::TARGET_GEM_NAME, TargetRailsVersion::USES_REQUIRES_GEM_API

Instance Method Summary collapse

Methods included from TargetRailsVersion

minimum_target_rails_version, support_target_rails_version?

Instance Method Details

#on_and(node) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/rubocop/cop/rails/env_local.rb', line 57

def on_and(node)
  rails_env_local_and?(node) do |*environments|
    next unless environments.to_set == LOCAL_ENVIRONMENTS

    add_offense(node, message: MSG_NEGATED) do |corrector|
      corrector.replace(node, '!Rails.env.local?')
    end
  end
end

#on_or(node) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/cop/rails/env_local.rb', line 47

def on_or(node)
  rails_env_local_or?(node) do |*environments|
    next unless environments.to_set == LOCAL_ENVIRONMENTS

    add_offense(node) do |corrector|
      corrector.replace(node, 'Rails.env.local?')
    end
  end
end

#rails_env_local_and?(node) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/rails/env_local.rb', line 36

def_node_matcher :rails_env_local_and?, <<~PATTERN
  (and
    (send
      (send (send (const {cbase nil? } :Rails) :env) $%LOCAL_ENVIRONMENTS)
      :!)
    (send
      (send (send (const {cbase nil? } :Rails) :env) $%LOCAL_ENVIRONMENTS)
      :!)
  )
PATTERN

#rails_env_local_or?(node) ⇒ Object



28
29
30
31
32
33
# File 'lib/rubocop/cop/rails/env_local.rb', line 28

def_node_matcher :rails_env_local_or?, <<~PATTERN
  (or
    (send (send (const {cbase nil? } :Rails) :env) $%LOCAL_ENVIRONMENTS)
    (send (send (const {cbase nil? } :Rails) :env) $%LOCAL_ENVIRONMENTS)
  )
PATTERN