class RuboCop::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_def(node)
click to toggle source
# File lib/rubocop/cop/style/guard_clause.rb, line 44 def on_def(node) body = node.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
Also aliased as: on_defs
on_if(node)
click to toggle source
# File lib/rubocop/cop/style/guard_clause.rb, line 57 def on_if(node) return if accepted_form?(node) || !contains_guard_clause?(node) add_offense(node, location: :keyword) end
Private Instance Methods
accepted_form?(node, ending = false)
click to toggle source
# File lib/rubocop/cop/style/guard_clause.rb, line 71 def accepted_form?(node, ending = false) accepted_if?(node, ending) || node.condition.multiline? end
accepted_if?(node, ending)
click to toggle source
# File lib/rubocop/cop/style/guard_clause.rb, line 75 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/rubocop/cop/style/guard_clause.rb, line 65 def check_ending_if(node) return if accepted_form?(node, true) || !min_body_length?(node) add_offense(node, location: :keyword) end
contains_guard_clause?(node)
click to toggle source
# File lib/rubocop/cop/style/guard_clause.rb, line 85 def contains_guard_clause?(node) node.if_branch && node.if_branch.guard_clause? || node.else_branch && node.else_branch.guard_clause? end