123456789_123456789_123456789_123456789_123456789_

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

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
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

DEPARTMENT_SEVERITIES, EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

::RuboCop::Cop::Alignment - Included

PRINTABLE_ASCII, SPACE

::RuboCop::Cop::StatementModifier - Included

SPACE_INSIDE_PARENS_STYLES

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 a 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

Reserved for Commissioner.

::RuboCop::ExcludeLimit - Extended

exclude_limit

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

transform

Instance Attribute Summary

::RuboCop::Cop::StatementModifier - Included

::RuboCop::Cop::LineLengthHelp - Included

::RuboCop::Cop::Alignment - Included

::RuboCop::Cop::Base - Inherited

::RuboCop::Cop::AutocorrectLogic - Included

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?,
#skipped_unsafe_correction_with_disable_uncorrectable?

Whether a correction exists but is skipped because it is unsafe in a safe autocorrect run, while --disable-uncorrectable asks for a todo comment on everything this run cannot correct.

#contextual_autocorrect_held_back?

When LSP is enabled or the --editor-mode option is on, it is considered as editing source code, and autocorrection with AutoCorrect: contextual will not be performed.

Instance Method Summary

::RuboCop::Cop::RescueNode - Included

::RuboCop::Cop::StatementModifier - Included

#acceptable_line_length?

Whether an existing line is acceptable to Layout/LineLength, exemptions (the cop disabled at that line, an allowed pattern, an allowed cop directive, an allowed URI) included.

#allowed_by_uri?,
#allowed_patterns

`Layout/LineLength’s allowed patterns, so a modifier line that the user has configured that cop to accept is not flagged for length here.

#code_after, #comment_disables_cop?, #first_line_comment,
#if_body_source

rubocop:disable-next Metrics/AbcSize.

#line_in_modifier_form, #line_length_enabled_at_line?, #method_source,
#modifier_fits_on_single_line?

The rendered modifier form is compared against the bare maximum, not acceptable_line_length?: `Layout/LineLength’s exemptions describe long lines the user tolerates, not permission to manufacture new ones, so collapsing to modifier form must never push a line past the maximum.

#non_eligible_body?, #non_eligible_condition?, #non_eligible_node?, #parenthesize?, #single_line_as_modifier?, #ternary_branch_or_endless_method_body?, #to_modifier_form, #unparenthesized_call_with_omitted_value?, #wrapped_value

::RuboCop::Cop::AllowedPattern - Included

::RuboCop::Cop::LineLengthHelp - Included

::RuboCop::Cop::Alignment - Included

::RuboCop::Cop::MinBodyLength - Included

::RuboCop::Cop::RangeHelp - Included

#add_range,
#arguments_range

A range containing the first to the last argument of a method call or method definition.

#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

rubocop:disable-next Metrics/ParameterLists.

#move_pos, #move_pos_str, #range_between, #range_by_whole_lines,
#range_for_statement_removal

Returns the range to remove a statement: its whole lines, including a trailing comment and the final newline, when no other code shares them, and otherwise the range itself with the spaces after it.

#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

 — grouped under the Commissioner heading above.

#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:

#file_independent_relevance

Whether relevant_file? has the same answer for every file: true or false when it does, and nil when the answer depends on the file.

#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 The source is parsed the way the file under investigation was.

#parser_engine,
#ready

Called between investigations.

#relevant_file?,
#target_gem_version

Returns the version of a gem in the target, by default its locked version (i.e. from Gemfile.lock or gems.locked).

#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, #covering_disabled_range, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?,
#enabled_lines?

A multi-line offense is suppressed by a directive on any line of its range, not only its first line, matching the intuition that the directive is attached to the offending code.

#file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #new_offense, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#suppression_reason

The -- reason on the directive that suppresses offenses on this range, or nil when the directive carries none.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

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

Class Method Details

.autocorrect_incompatible_with

[ GitHub ]

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

def self.autocorrect_incompatible_with
  [Style::MissingElse]
end

Instance Attribute Details

#allowed_consecutive_conditionals? ⇒ Boolean (readonly, private)

[ GitHub ]

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

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 301

def accepted_form?(node, ending: false)
  return true if accepted_if?(node, ending) || node.condition.multiline?

  !statement?(node)
end

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

[ GitHub ]

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

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

  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 291

def and_or_guard_clause?(guard_clause)
  parent = guard_clause.parent
  parent.operator_keyword?
end

#assigned_lvar_used_in_if_branch?(node) ⇒ Boolean (private)

[ GitHub ]

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

def assigned_lvar_used_in_if_branch?(node)
  return false unless (if_branch = node.if_branch)

  assigned_lvars_in_condition = node.condition.each_descendant(:lvasgn).map do |lvasgn|
    lvar_name, = *lvasgn
    lvar_name.to_s
  end
  used_lvars_in_branch = if_branch.each_descendant(:lvar).map(&:source) || []

  (assigned_lvars_in_condition & used_lvars_in_branch).any?
end

#autocorrect(corrector, node, example, multiline_replacement, guard) (private)

rubocop:disable-next Metrics/AbcSize

[ GitHub ]

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

def autocorrect(corrector, node, example, multiline_replacement, guard)
  range = node.loc.keyword.join(node.condition.source_range)
  corrector.replace(range, multiline_replacement || example)
  corrector.replace(node.loc.begin, "\n") if node.then?

  branches = [node.if_branch, node.else_branch]
  guard_branch, leave_branch = guard == :else ? branches.reverse : branches

  heredoc = find_heredoc_argument(guard_branch)
  close_multiline_guard_clause(corrector, range, heredoc, guard) if multiline_replacement

  if heredoc
    return autocorrect_heredoc_argument(corrector, node, heredoc, leave_branch, guard)
  end

  corrector.remove(node.loc.end)
  return unless node.else?

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

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

[ GitHub ]

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

def autocorrect_heredoc_argument(corrector, node, heredoc_node, leave_branch, guard)
  remove_end(corrector, node.loc.end)
  return unless node.else?

  if leave_branch
    remove_whole_lines(corrector, leave_branch.source_range)
    corrector.insert_after(heredoc_node.loc.heredoc_end, "\n#{leave_branch.source}")
  end

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

#check_ending_body(body) (private)

[ GitHub ]

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

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 168

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

#close_multiline_guard_clause(corrector, range, heredoc, guard) (private)

[ GitHub ]

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

def close_multiline_guard_clause(corrector, range, heredoc, guard)
  corrector.insert_after(guard && heredoc ? heredoc.loc.heredoc_end : range, "\nend")
end

#code_after_end_needs_conditional?(node, guard) ⇒ Boolean (private)

[ GitHub ]

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

def code_after_end_needs_conditional?(node, guard)
  guard_branch = guard == :else ? node.else_branch : node.if_branch
  return false unless find_heredoc_argument(guard_branch)

  end_keyword = node.loc.end

  !end_keyword.source_line[end_keyword.last_column..].match?(/\A\s*(?:\z|[#;)\]}])/)
end

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

[ GitHub ]

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

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

#find_heredoc_argument(node) (private)

[ GitHub ]

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

def find_heredoc_argument(node)
  return unless (node = unwrap_begin(node))
  return node if heredoc?(node)
  return unless node.call_type?

  node.arguments.reverse_each do |argument|
    heredoc_argument = find_heredoc_argument(argument)
    return heredoc_argument if heredoc_argument
  end

  find_heredoc_argument(node.receiver)
end

#guard_clause_source(guard_clause) (private)

[ GitHub ]

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

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)

[ GitHub ]

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

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

#on_block(node) Also known as: #on_numblock, #on_itblock

[ GitHub ]

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

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 120

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 127

alias on_defs on_def

#on_if(node)

[ GitHub ]

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

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_itblock(node)

Alias for #on_block.

[ GitHub ]

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

alias on_itblock on_block

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

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

alias on_numblock on_block

#range_of_branch_to_remove(node, guard) (private)

[ GitHub ]

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

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 186

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 = "#{conditional_keyword} #{condition.source}\n  #{scope_exiting_keyword}"
  end

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

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

#remove_end(corrector, end_range) (private)

[ GitHub ]

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

def remove_end(corrector, end_range)
  if range_by_whole_lines(end_range).source.strip == end_range.source
    remove_whole_lines(corrector, end_range)
  else
    corrector.remove(end_range)
  end
end

#remove_whole_lines(corrector, range) (private)

[ GitHub ]

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

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

#statement?(node) ⇒ Boolean (private)

A guard clause is followed by the rest of the code as separate statements, so there is no room for them where a single expression is expected, such as an assignment value, a hash value, or the body of an endless method.

[ GitHub ]

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

def statement?(node)
  parent = node.parent
  return true if parent.nil? || parent.type?(*STATEMENT_PARENT_TYPES)
  return !parent.endless? if parent.any_def_type?
  return !rescue_modifier?(parent) if parent.resbody_type?
  return !rescue_modifier?(parent.resbody_branches.first) if parent.rescue_type?

  statement_branch?(node, parent)
end

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

[ GitHub ]

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

def statement_branch?(node, parent)
  case parent.type
  when :if
    !parent.ternary? && !node.equal?(parent.condition)
  when :when, :in_pattern, :while, :until, :for
    node.equal?(parent.body)
  when :case, :case_match
    node.equal?(parent.else_branch)
  else
    false
  end
end

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

[ GitHub ]

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

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 333

def trivial?(node)
  return false unless node.if_branch

  node.branches.one? && !node.if_branch.if_type? && !node.if_branch.begin_type?
end

#unwrap_begin(node) (private)

[ GitHub ]

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

def unwrap_begin(node)
  node = node.children.first while node&.begin_type?
  node
end