123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::RedundantBegin

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/redundant_begin.rb

Overview

Checks for redundant begin blocks. A begin block is redundant when the rescue/ensure can be handled by the enclosing method or block definition directly, avoiding unnecessary indentation.

Examples:

# bad
def redundant
  begin
    ala
    bala
  rescue StandardError => e
    something
  end
end

# good
def preferred
  ala
  bala
rescue StandardError => e
  something
end

# bad
begin
  do_something
end

# good
do_something

# bad
# When using Ruby 2.5 or later.
do_something do
  begin
    something
  rescue => ex
    anything
  end
end

# good
# In Ruby 2.5 or later, you can omit {begin} in {do-end} block.
do_something do
  something
rescue => ex
  anything
end

# good
# Stabby lambdas don't support implicit {begin} in {do-end} blocks.
-> do
  begin
    foo
  rescue Bar
    baz
  end
end

Constant Summary

::RuboCop::Cop::Base - Inherited

DEPARTMENT_SEVERITIES, EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

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

#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_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/redundant_begin.rb', line 76

def self.autocorrect_incompatible_with
  [
    Style::BlockDelimiters,
    Style::TrailingCommaInArguments,
    Style::TrailingCommaInArrayLiteral,
    Style::TrailingCommaInHashLiteral
  ]
end

Instance Attribute Details

#space_inside_parens? ⇒ Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 328

def space_inside_parens?
  return false unless config.cop_enabled?('Layout/SpaceInsideParens')

  style = config.for_cop('Layout/SpaceInsideParens')['EnforcedStyle']

  SPACE_INSIDE_PARENS_STYLES.include?(style)
end

Instance Method Details

#allowable_kwbegin?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 141

def allowable_kwbegin?(node)
  empty_begin?(node) ||
    begin_block_has_multiline_statements?(node) ||
    contain_rescue_or_ensure?(node) ||
    valid_context_using_only_begin?(node) ||
    ternary_operand_requiring_begin?(node)
end

#begin_block_has_multiline_statements?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 284

def begin_block_has_multiline_statements?(node)
  return false unless node.parent

  node.children.count >= 2
end

#code_after_end_on_its_own_line?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 179

def code_after_end_on_its_own_line?(node)
  end_range = node.loc.end
  return false unless begins_its_line?(end_range)

  rest_of_line = end_range.source_line[end_range.last_column..].lstrip

  !rest_of_line.empty? && !rest_of_line.start_with?('#')
end

#command_call?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 226

def command_call?(node)
  node = node.send_node if node.any_block_type?
  return false unless node.type?(:call, :super, :yield)

  node.arguments? && !node.parenthesized? && !node.operator_method? && !node.setter_method?
end

#condition_range(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 276

def condition_range(node)
  range_between(node.loc.keyword.begin_pos, node.condition.source_range.end_pos)
end

#contain_rescue_or_ensure?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 290

def contain_rescue_or_ensure?(node)
  first_child = node.children.first

  first_child.type?(:rescue, :ensure)
end

#correct_end(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 259

def correct_end(corrector, node)
  if use_modifier_form_after_multiline_begin_block?(node)
    correct_modifier_form_after_multiline_begin_block(corrector, node)
  elsif code_after_end_on_its_own_line?(node)
    corrector.remove(range_with_end_line_break(node))
  else
    corrector.remove(node.loc.end)
  end
end

#correct_modifier_form_after_multiline_begin_block(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 269

def correct_modifier_form_after_multiline_begin_block(corrector, node)
  condition_range = condition_range(node.parent)

  corrector.insert_after(node.children.first, " #{condition_range.source}")
  corrector.remove(range_by_whole_lines(condition_range, include_final_newline: true))
end

#empty_begin?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 280

def empty_begin?(node)
  node.children.empty?
end

#end_cannot_join_statement_line?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 165

def end_cannot_join_statement_line?(node)
  return false if use_modifier_form_after_multiline_begin_block?(node)
  return false unless code_after_end_on_its_own_line?(node)

  range_with_end_line_break(node).begin_pos != statement_end_pos(node)
end

#inspect_branches(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 336

def inspect_branches(node)
  node.branches.each do |branch|
    next unless branch&.kwbegin_type?
    next if branch.ensure_node || branch.rescue_node
    next if ternary_operand_requiring_begin?(branch)

    register_offense(branch)
  end
end

#low_precedence_statement?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 219

def low_precedence_statement?(node)
  return node.modifier_form? if node.basic_conditional?
  return node.prefix_not? if node.send_type?

  node.operator_keyword? && node.semantic_operator?
end

#offensive_kwbegins(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 86

def_node_search :offensive_kwbegins, <<~PATTERN
  [(kwbegin ...) !#allowable_kwbegin?]
PATTERN

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

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 121

def on_block(node)
  return if target_ruby_version < 2.5
  return if node.send_node.lambda_literal?
  return if node.braces?
  return unless node.body&.kwbegin_type?

  register_offense(node.body)
end

#on_case(node) Also known as: #on_case_match

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 104

def on_case(node)
  inspect_branches(node)
end

#on_case_match(node)

Alias for #on_case.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 107

alias on_case_match on_case

#on_def(node) Also known as: #on_defs

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 90

def on_def(node)
  return unless node.body&.kwbegin_type?
  return if node.endless?

  register_offense(node.body)
end

#on_defs(node)

Alias for #on_def.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 96

alias on_defs on_def

#on_if(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 98

def on_if(node)
  return if node.modifier_form?

  inspect_branches(node)
end

#on_itblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 131

alias on_itblock on_block

#on_kwbegin(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 133

def on_kwbegin(node)
  return unless (target_node = offensive_kwbegins(node).to_a.last)

  register_offense(target_node)
end

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

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

alias on_numblock on_block

#on_until(node)

Alias for #on_while.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 119

alias on_until on_while

#on_while(node) Also known as: #on_until

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 109

def on_while(node)
  return if node.modifier_form?

  body = node.body

  return unless body&.kwbegin_type?
  return if body.ensure_node || body.rescue_node

  register_offense(body)
end

#parentheses_required?(statement, parent) ⇒ Boolean (private)

[ GitHub ]

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

def parentheses_required?(statement, parent)
  return true if low_precedence_statement?(statement)
  return false unless command_call?(statement)
  return parent.type?(:optarg, :kwoptarg) unless parent.assignment?

  parent = parent.parent while parent.parent&.assignment?
  !statement_position?(parent)
end

#parentheses_width (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 324

def parentheses_width
  space_inside_parens? ? 4 : 2
end

#range_with_end_line_break(node) (private)

[ GitHub ]

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

def range_with_end_line_break(node)
  range_with_surrounding_space(node.loc.end, side: :left, newlines: true)
end

#register_offense(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 149

def register_offense(node)
  return if end_cannot_join_statement_line?(node)

  offense_range = node.loc.begin

  add_offense(offense_range) do |corrector|
    if node.parent&.assignment? || node.parent&.type?(*VALUE_PARENT_TYPES)
      replace_begin_with_statement(corrector, offense_range, node)
    else
      remove_begin(corrector, offense_range, node)
    end

    correct_end(corrector, node)
  end
end

#remove_begin(corrector, offense_range, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 242

def remove_begin(corrector, offense_range, node)
  if node.parent.respond_to?(:endless?) && node.parent.endless?
    offense_range = range_with_surrounding_space(offense_range, newlines: true)
  end

  corrector.remove(offense_range)
end

#replace_begin_with_statement(corrector, offense_range, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 198

def replace_begin_with_statement(corrector, offense_range, node)
  first_child = node.children.first

  source = first_child.source
  source = "(#{source})" if parentheses_required?(first_child, node.parent)

  corrector.replace(offense_range, source)
  corrector.remove(range_between(offense_range.end_pos, first_child.source_range.end_pos))

  restore_removed_comments(corrector, offense_range, node, first_child)
end

#restore_removed_comments(corrector, offense_range, node, first_child) (private)

Restore comments that occur between "begin" and "first_child". These comments will be moved to above the assignment line.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 252

def restore_removed_comments(corrector, offense_range, node, first_child)
  comments_range = range_between(offense_range.end_pos, first_child.source_range.begin_pos)
  comments = comments_range.source

  corrector.insert_before(node.parent, comments) unless comments.blank?
end

#statement_end_pos(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 192

def statement_end_pos(node)
  return node.loc.begin.end_pos if node.children.empty?

  node.children.last.source_range.end_pos
end

#statement_position?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 233

def statement_position?(node)
  parent = node.parent
  return true if parent.nil? || parent.type?(*STATEMENT_CONTAINER_TYPES)
  return parent.body.equal?(node) if parent.type?(:when, :in_pattern, :for)
  return false if parent.if_type? && parent.ternary?

  parent.type?(:if, :while, :until, :case, :case_match) && !parent.condition.equal?(node)
end

#ternary_operand_requiring_begin?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 303

def ternary_operand_requiring_begin?(node)
  return false unless node.parent&.if_type? && node.parent.ternary?

  !node.children.one? || low_precedence_statement?(node.children.first)
end

#too_long_when_joined?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 313

def too_long_when_joined?(node)
  statement = node.children.first
  max = config.for_enabled_cop('Layout/LineLength')['Max']
  return false unless max && statement.single_line?

  length = statement.source.length
  length += parentheses_width if low_precedence_statement?(statement)

  node.loc.column + length > max
end

#use_modifier_form_after_multiline_begin_block?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 172

def use_modifier_form_after_multiline_begin_block?(node)
  return false unless (parent = node.parent)
  return false unless node.multiline? && parent.if_type? && parent.modifier_form?

  !parent.condition.equal?(node)
end

#valid_begin_assignment?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_begin.rb', line 309

def valid_begin_assignment?(node)
  node.parent&.assignment? && (!node.children.one? || too_long_when_joined?(node))
end

#valid_context_using_only_begin?(node) ⇒ Boolean (private)

[ GitHub ]

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

def valid_context_using_only_begin?(node)
  parent = node.parent

  valid_begin_assignment?(node) || parent&.post_condition_loop? ||
    parent&.send_type? || parent&.operator_keyword?
end