Class: RuboCop::Cop::Rails::EnvironmentComparison

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

Overview

Checks that Rails.env is compared using ‘.production?`-like methods instead of equality against a string or symbol.

Examples:

# bad
Rails.env == 'production'

# bad, always returns false
Rails.env == :test

# good
Rails.env.production?

Constant Summary collapse

MSG =
'Favor `%<bang>sRails.env.%<env>s?` over `%<source>s`.'
SYM_MSG =
'Do not compare `Rails.env` with a symbol, it will always evaluate to `false`.'
RESTRICT_ON_SEND =
%i[== !=].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/rubocop/cop/rails/environment_comparison.rb', line 63

def on_send(node)
  if (env_node = comparing_str_env_with_rails_env_on_lhs?(node) ||
                 comparing_str_env_with_rails_env_on_rhs?(node))
    env, = *env_node
    bang = node.method?(:!=) ? '!' : ''
    message = format(MSG, bang: bang, env: env, source: node.source)

    add_offense(node, message: message) do |corrector|
      autocorrect(corrector, node)
    end
  end

  return unless comparing_sym_env_with_rails_env_on_lhs?(node) || comparing_sym_env_with_rails_env_on_rhs?(node)

  add_offense(node, message: SYM_MSG) do |corrector|
    autocorrect(corrector, node)
  end
end