Class: RuboCop::Cop::Style::YodaExpression

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

Overview

Forbids Yoda expressions, i.e. binary operations (using ‘*`, `+`, `&`, `|`, and `^` operators) where the order of expression is reversed, eg. `1 + x`. This cop complements `Style/YodaCondition` cop, which has a similar purpose.

This cop is disabled by default to respect user intentions such as:

source,ruby

config.server_port = 9000 + ENV.to_i


Examples:

SupportedOperators: [‘*’, ‘+’, ‘&’, ‘|’, ‘^’] (default)

# bad
10 * y
1 + x
1 & z
1 | x
1 ^ x
1 + CONST

# good
y * 10
x + 1
z & 1
x | 1
x ^ 1
CONST + 1
60 * 24

Constant Summary collapse

MSG =
'Non-literal operand (`%<source>s`) should be first.'
RESTRICT_ON_SEND =
%i[* + & | ^].freeze

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source

Instance Method Summary collapse

Methods included from AutoCorrector

support_autocorrect?

Methods inherited from Base

#active_support_extensions_enabled?, #add_global_offense, #add_offense, #always_autocorrect?, autocorrect_incompatible_with, badge, #begin_investigation, #callbacks_needed, callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #contextual_autocorrect?, #cop_config, cop_name, #cop_name, department, documentation_url, exclude_from_registry, #excluded_file?, #external_dependency_checksum, inherited, #initialize, #inspect, joining_forces, lint?, match?, #message, #offenses, #on_investigation_end, #on_other_file, #parse, #parser_engine, #ready, #relevant_file?, requires_gem, support_autocorrect?, support_multiple_source?, #target_rails_version, #target_ruby_version

Methods included from ExcludeLimit

#exclude_limit

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

silence_warnings

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Method Details

#on_new_investigationObject



47
48
49
# File 'lib/rubocop/cop/style/yoda_expression.rb', line 47

def on_new_investigation
  @offended_nodes = nil
end

#on_send(node) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rubocop/cop/style/yoda_expression.rb', line 51

def on_send(node)
  return unless supported_operators.include?(node.method_name.to_s)

  lhs = node.receiver
  rhs = node.first_argument
  return unless yoda_expression_constant?(lhs, rhs)
  return if offended_ancestor?(node)

  message = format(MSG, source: rhs.source)
  add_offense(node, message: message) do |corrector|
    corrector.swap(lhs, rhs)
  end

  offended_nodes.add(node)
end