123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::GuardClause

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/guard_clause.rb

Overview

Use a guard clause instead of wrapping the code inside a conditional expression

A condition with an elsif or else branch is allowed unless one of return, break, next, raise, or fail is used in the body of the conditional expression.

Note
Autocorrect works in most cases except with if-else statements that contain logical operators such as foo || raise('exception')

Examples:

# 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

# bad
if something
  foo || raise('exception')
else
  ok
end

# good
foo || raise('exception') if something
ok

# bad
define_method(:test) do
  if something
    work
  end
end

# good
define_method(:test) do
  return unless something

  work
end

# also good
define_method(:test) do
  work if something
end

AllowConsecutiveConditionals: false (default)

# bad
def test
  if foo?
    work
  end

  if bar?  # <- reports an offense
    work
  end
end

AllowConsecutiveConditionals: true

# good
def test
  if foo?
    work
  end

  if bar?
    work
  end
end

# bad
def test
  if foo?
    work
  end

  do_something

  if bar?  # <- reports an offense
    work
  end
end

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

::RuboCop::Cop::Alignment - Included

SPACE

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Returns an url to view this cops documentation online.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::StatementModifier - Included

::RuboCop::Cop::LineLengthHelp - Included

::RuboCop::Cop::Alignment - Included

::RuboCop::Cop::MinBodyLength - Included

::RuboCop::Cop::RangeHelp - Included

#add_range, #column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos, #move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed,
#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?, #target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Attribute Details

#allowed_consecutive_conditionals?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 297

def allowed_consecutive_conditionals?
  cop_config.fetch('AllowConsecutiveConditionals', false)
end

Instance Method Details

#accepted_form?(node, ending: false) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 275

def accepted_form?(node, ending: false)
  accepted_if?(node, ending) || node.condition.multiline? || node.parent&.assignment?
end

#accepted_if?(node, ending) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 283

def accepted_if?(node, ending)
  return true if node.modifier_form? || node.ternary? || node.elsif_conditional?

  if ending
    node.else?
  else
    !node.else? || node.elsif?
  end
end

#and_or_guard_clause?(guard_clause) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 265

def and_or_guard_clause?(guard_clause)
  parent = guard_clause.parent
  parent.and_type? || parent.or_type?
end

#autocorrect(corrector, node, condition, replacement, guard) (private)

Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 210

def autocorrect(corrector, node, condition, replacement, guard)
  corrector.replace(node.loc.keyword.join(condition.source_range), replacement)

  if_branch = node.if_branch
  else_branch = node.else_branch

  corrector.replace(node.loc.begin, "\n") if node.loc.begin&.is?('then')

  if if_branch&.send_type? && heredoc?(if_branch.last_argument)
    autocorrect_heredoc_argument(corrector, node, if_branch, else_branch, guard)
  elsif else_branch&.send_type? && heredoc?(else_branch.last_argument)
    autocorrect_heredoc_argument(corrector, node, else_branch, if_branch, guard)
  else
    corrector.remove(node.loc.end)
    return unless node.else?

    corrector.remove(node.loc.else)
    corrector.remove(range_of_branch_to_remove(node, guard))
  end
end

#autocorrect_heredoc_argument(corrector, node, heredoc_branch, leave_branch, guard) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 236

def autocorrect_heredoc_argument(corrector, node, heredoc_branch, leave_branch, guard)
  return unless node.else?

  remove_whole_lines(corrector, leave_branch.source_range)
  remove_whole_lines(corrector, node.loc.else)
  remove_whole_lines(corrector, node.loc.end)
  remove_whole_lines(corrector, range_of_branch_to_remove(node, guard))
  corrector.insert_after(
    heredoc_branch.last_argument.loc.heredoc_end, "\n#{leave_branch.source}"
  )
end

#check_ending_body(body) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 159

def check_ending_body(body)
  return if body.nil?

  if body.if_type?
    check_ending_if(body)
  elsif body.begin_type?
    final_expression = body.children.last
    check_ending_if(final_expression) if final_expression&.if_type?
  end
end

#check_ending_if(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 170

def check_ending_if(node)
  return if accepted_form?(node, ending: true) || !min_body_length?(node)
  return if allowed_consecutive_conditionals? &&
            consecutive_conditionals?(node.parent, node)

  register_offense(node, 'return', node.inverse_keyword)

  check_ending_body(node.if_branch)
end

#consecutive_conditionals?(parent, node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 180

def consecutive_conditionals?(parent, node)
  parent.each_child_node.inject(false) do |if_type, child|
    break if_type if node == child

    child.if_type?
  end
end

#guard_clause_source(guard_clause) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 257

def guard_clause_source(guard_clause)
  if and_or_guard_clause?(guard_clause)
    guard_clause.parent.source
  else
    guard_clause.source
  end
end

#heredoc?(argument) ⇒ Boolean (private)

Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 232

def heredoc?(argument)
  argument.respond_to?(:heredoc?) && argument.heredoc?
end

#on_block(node) Also known as: #on_numblock

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 132

def on_block(node)
  return unless node.method?(:define_method) || node.method?(:define_singleton_method)

  on_def(node)
end

#on_def(node) Also known as: #on_defs

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 123

def on_def(node)
  body = node.body

  return unless body

  check_ending_body(body)
end

#on_defs(node)

Alias for #on_def.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 130

alias on_defs on_def

#on_if(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 139

def on_if(node)
  return if accepted_form?(node)

  if (guard_clause = node.if_branch&.guard_clause?)
    kw = node.loc.keyword.source
    guard = :if
  elsif (guard_clause = node.else_branch&.guard_clause?)
    kw = node.inverse_keyword
    guard = :else
  else
    return
  end

  guard = nil if and_or_guard_clause?(guard_clause)

  register_offense(node, guard_clause_source(guard_clause), kw, guard)
end

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 137

alias on_numblock on_block

#range_of_branch_to_remove(node, guard) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 248

def range_of_branch_to_remove(node, guard)
  branch = case guard
           when :if then node.if_branch
           when :else then node.else_branch
           end

  branch.source_range
end

#register_offense(node, scope_exiting_keyword, conditional_keyword, guard = nil) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 188

def register_offense(node, scope_exiting_keyword, conditional_keyword, guard = nil)
  condition, = node.node_parts
  example = [scope_exiting_keyword, conditional_keyword, condition.source].join(' ')
  if too_long_for_single_line?(node, example)
    return if trivial?(node)

    example = "#{conditional_keyword} #{condition.source}; #{scope_exiting_keyword}; end"
    replacement = <<~RUBY.chomp
      #{conditional_keyword} #{condition.source}
        #{scope_exiting_keyword}
      end
    RUBY
  end

  add_offense(node.loc.keyword, message: format(MSG, example: example)) do |corrector|
    next if node.else? && guard.nil?

    autocorrect(corrector, node, condition, replacement || example, guard)
  end
end

#remove_whole_lines(corrector, range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 293

def remove_whole_lines(corrector, range)
  corrector.remove(range_by_whole_lines(range, include_final_newline: true))
end

#too_long_for_single_line?(node, example) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 270

def too_long_for_single_line?(node, example)
  max = max_line_length
  max && node.source_range.column + example.length > max
end

#trivial?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/guard_clause.rb', line 279

def trivial?(node)
  node.branches.one? && !node.if_branch.if_type? && !node.if_branch.begin_type?
end