class RuboCop::Cop::Style::NestedModifier
This cop checks for nested use of if, unless, while and until in their modifier form.
@example
# bad something if a if b # good something if b && a
Constants
- MSG
Public Instance Methods
autocorrect(node)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 43 def autocorrect(node) return unless node.if_type? && node.parent.if_type? range = range_between(node.loc.keyword.begin_pos, node.parent.condition.source_range.end_pos) lambda do |corrector| corrector.replace(range, new_expression(node.parent, node)) end end
check(node)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 31 def check(node) return if part_of_ignored_node?(node) return unless modifier?(node) && modifier?(node.parent) add_offense(node, location: :keyword) ignore_node(node) end
left_hand_operand(node, operator)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 66 def left_hand_operand(node, operator) expr = node.condition.source expr = "(#{expr})" if node.condition.or_type? && operator == '&&'.freeze expr end
modifier?(node)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 39 def modifier?(node) node && MODIFIER_NODES.include?(node.type) && node.modifier_form? end
new_expression(outer_node, inner_node)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 54 def new_expression(outer_node, inner_node) operator = replacement_operator(outer_node.keyword) lh_operand = left_hand_operand(outer_node, operator) rh_operand = right_hand_operand(inner_node, outer_node.keyword) "#{outer_node.keyword} #{lh_operand} #{operator} #{rh_operand}" end
on_if(node)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 27 def on_if(node) check(node) end
on_until(node)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 23 def on_until(node) check(node) end
on_while(node)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 19 def on_while(node) check(node) end
replacement_operator(keyword)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 62 def replacement_operator(keyword) keyword == 'if'.freeze ? '&&'.freeze : '||'.freeze end
requires_parens?(node)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 80 def requires_parens?(node) node.or_type? || !(RuboCop::AST::Node::COMPARISON_OPERATORS & node.children).empty? end
right_hand_operand(node, left_hand_keyword)
click to toggle source
# File lib/rubocop/cop/style/nested_modifier.rb, line 73 def right_hand_operand(node, left_hand_keyword) expr = node.condition.source expr = "(#{expr})" if requires_parens?(node.condition) expr = "!#{expr}" unless left_hand_keyword == node.keyword expr end