class RubbyCop::Cop::Style::GuardClause
Use a guard clause instead of wrapping the code inside a conditional expression
@example
# bad def test if something work end end # good def test return unless something work end # also good def test work if something end # bad if something raise 'exception' else ok end # good raise 'exception' if something ok
Constants
- MSG
Public Instance Methods
on_if(node)
click to toggle source
# File lib/rubbycop/cop/style/guard_clause.rb, line 55 def on_if(node) return if accepted_form?(node) || !contains_guard_clause?(node) add_offense(node, :keyword) end
on_method_def(_node, _method_name, _args, body)
click to toggle source
# File lib/rubbycop/cop/style/guard_clause.rb, line 45 def on_method_def(_node, _method_name, _args, body) return unless body if body.if_type? check_ending_if(body) elsif body.begin_type? && body.children.last.if_type? check_ending_if(body.children.last) end end
Private Instance Methods
accepted_form?(node, ending = false)
click to toggle source
# File lib/rubbycop/cop/style/guard_clause.rb, line 69 def accepted_form?(node, ending = false) accepted_if?(node, ending) || node.condition.multiline? end
accepted_if?(node, ending)
click to toggle source
# File lib/rubbycop/cop/style/guard_clause.rb, line 73 def accepted_if?(node, ending) return true if node.modifier_form? || node.ternary? if ending node.else? else !node.else? || node.elsif? end end
check_ending_if(node)
click to toggle source
# File lib/rubbycop/cop/style/guard_clause.rb, line 63 def check_ending_if(node) return if accepted_form?(node, true) || !min_body_length?(node) add_offense(node, :keyword) end
contains_guard_clause?(node)
click to toggle source
# File lib/rubbycop/cop/style/guard_clause.rb, line 83 def contains_guard_clause?(node) node.if_branch && node.if_branch.guard_clause? || node.else_branch && node.else_branch.guard_clause? end