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.

Currently it checks for code like this:

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

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

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

Returns a gems locked versions (i.e.

#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

Class Method Details

.autocorrect_incompatible_with

[ GitHub ]

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

def self.autocorrect_incompatible_with
  [Style::BlockDelimiters]
end

Instance Method Details

#allowable_kwbegin?(node) ⇒ Boolean (private)

[ GitHub ]

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

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

#begin_block_has_multiline_statements?(node) ⇒ Boolean (private)

[ GitHub ]

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

def begin_block_has_multiline_statements?(node)
  node.children.count >= 2
end

#condition_range(node) (private)

[ GitHub ]

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

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 185

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

  first_child.rescue_type? || first_child.ensure_type?
end

#correct_modifier_form_after_multiline_begin_block(corrector, node) (private)

[ GitHub ]

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

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 177

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

#offensive_kwbegins(node)

[ GitHub ]

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

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

#on_block(node) Also known as: #on_numblock

[ GitHub ]

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

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_def(node) Also known as: #on_defs

[ GitHub ]

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

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 86

alias on_defs on_def

#on_kwbegin(node)

[ GitHub ]

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

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 97

alias on_numblock on_block

#register_offense(node) (private)

[ GitHub ]

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

def register_offense(node)
  offense_range = node.loc.begin

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

    if use_modifier_form_after_multiline_begin_block?(node)
      correct_modifier_form_after_multiline_begin_block(corrector, node)
    end
    corrector.remove(node.loc.end)
  end
end

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

[ GitHub ]

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

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 131

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

  source = first_child.source
  source = "(#{source})" if first_child.if_type? && first_child.modifier_form?

  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 153

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

#use_modifier_form_after_multiline_begin_block?(node) ⇒ Boolean (private)

[ GitHub ]

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

def use_modifier_form_after_multiline_begin_block?(node)
  return false unless (parent = node.parent)

  node.multiline? && parent.if_type? && parent.modifier_form?
end

#valid_begin_assignment?(node) ⇒ Boolean (private)

[ GitHub ]

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

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

#valid_context_using_only_begin?(node) ⇒ Boolean (private)

[ GitHub ]

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

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