class RubbyCop::Cop::Style::OneLineConditional
TODO: Make configurable. Checks for uses of if/then/else/end on a single line.
Constants
- MSG
Public Instance Methods
autocorrect(node)
click to toggle source
# File lib/rubbycop/cop/style/one_line_conditional.rb, line 20 def autocorrect(node) lambda do |corrector| corrector.replace(node.source_range, replacement(node)) end end
expr_replacement(node)
click to toggle source
# File lib/rubbycop/cop/style/one_line_conditional.rb, line 46 def expr_replacement(node) requires_parentheses?(node) ? "(#{node.source})" : node.source end
keyword_with_changed_precedence?(node)
click to toggle source
# File lib/rubbycop/cop/style/one_line_conditional.rb, line 66 def keyword_with_changed_precedence?(node) return false unless node.keyword? return true if node.keyword_not? !parenthesized_call?(node) end
method_call_with_changed_precedence?(node)
click to toggle source
# File lib/rubbycop/cop/style/one_line_conditional.rb, line 58 def method_call_with_changed_precedence?(node) return false unless node.send_type? return false if node.method_args.empty? return false if parenthesized_call?(node) !operator?(node.method_name) end
on_normal_if_unless(node)
click to toggle source
# File lib/rubbycop/cop/style/one_line_conditional.rb, line 14 def on_normal_if_unless(node) return unless node.single_line? && node.else_branch add_offense(node, :expression, format(MSG, node.keyword)) end
replacement(node)
click to toggle source
# File lib/rubbycop/cop/style/one_line_conditional.rb, line 26 def replacement(node) return to_ternary(node) unless node.parent if %i[and or].include?(node.parent.type) return "(#{to_ternary(node)})" end if node.parent.send_type? && operator?(node.parent.method_name) return "(#{to_ternary(node)})" end to_ternary(node) end
requires_parentheses?(node)
click to toggle source
# File lib/rubbycop/cop/style/one_line_conditional.rb, line 50 def requires_parentheses?(node) return true if %i[and or if].include?(node.type) return true if node.assignment? return true if method_call_with_changed_precedence?(node) keyword_with_changed_precedence?(node) end
to_ternary(node)
click to toggle source
# File lib/rubbycop/cop/style/one_line_conditional.rb, line 40 def to_ternary(node) cond, body, else_clause = *node "#{expr_replacement(cond)} ? #{expr_replacement(body)} : " \ "#{expr_replacement(else_clause)}" end