class RuboCop::Cop::Style::YodaCondition
This cop checks for Yoda conditions, i.e. comparison operations where readability is reduced because the operands are not ordered the same way as they would be ordered in spoken English.
@example
# EnforcedStyle: all_comparison_operators # bad 99 == foo "bar" != foo 42 >= foo 10 < bar # good foo == 99 foo == "bar" foo <= 42 bar > 10
@example
# EnforcedStyle: equality_operators_only # bad 99 == foo "bar" != foo # good 99 >= foo 3 < a && a < 5
Constants
- EQUALITY_OPERATORS
- MSG
- NONCOMMUTATIVE_OPERATORS
- REVERSE_COMPARISON
Public Instance Methods
on_send(node)
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 53 def on_send(node) return unless yoda_condition?(node) add_offense(node) end
Private Instance Methods
actual_code_range(node)
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 89 def actual_code_range(node) range_between( node.loc.expression.begin_pos, node.loc.expression.end_pos ) end
autocorrect(node)
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 78 def autocorrect(node) lambda do |corrector| corrector.replace(actual_code_range(node), corrected_code(node)) end end
check_equality_only?()
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 99 def check_equality_only? style == :equality_operators_only end
corrected_code(node)
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 84 def corrected_code(node) lhs, operator, rhs = *node "#{rhs.source} #{reverse_comparison(operator)} #{lhs.source}" end
message(node)
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 74 def message(node) format(MSG, node.source) end
non_equality_operator?(operator)
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 103 def non_equality_operator?(operator) !EQUALITY_OPERATORS.include?(operator) end
noncommutative_operator?(operator)
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 107 def noncommutative_operator?(operator) NONCOMMUTATIVE_OPERATORS.include?(operator) end
reverse_comparison(operator)
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 95 def reverse_comparison(operator) REVERSE_COMPARISON.fetch(operator.to_s, operator) end
yoda_condition?(node)
click to toggle source
# File lib/rubocop/cop/style/yoda_condition.rb, line 61 def yoda_condition?(node) return false unless node.comparison_method? lhs, operator, rhs = *node if check_equality_only? return false if non_equality_operator?(operator) end return false if noncommutative_operator?(operator) lhs.literal? && !rhs.literal? end