123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::ItBlockParameter

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/it_block_parameter.rb

Overview

Checks for blocks with one argument where it block parameter can be used.

It provides four EnforcedStyle options:

  1. allow_single_line (default) …​ Always uses the it block parameter in a single line.

  2. only_numbered_parameters …​ Detects only numbered block parameters.

  3. always …​ Always uses the it block parameter.

  4. disallow …​ Disallows the it block parameter.

A single numbered parameter is detected when allow_single_line, only_numbered_parameters, or always.

Examples:

EnforcedStyle: allow_single_line (default)

# bad
block do
  do_something(it)
end
block { do_something(_1) }

# good
block { do_something(it) }
block { |named_param| do_something(named_param) }

EnforcedStyle: only_numbered_parameters

# bad
block { do_something(_1) }

# good
block { do_something(it) }
block { |named_param| do_something(named_param) }

EnforcedStyle: always

# bad
block { do_something(_1) }
block { |named_param| do_something(named_param) }

# good
block { do_something(it) }

EnforcedStyle: disallow

# bad
block { do_something(it) }

# good
block { do_something(_1) }
block { |named_param| do_something(named_param) }

Constant Summary

::RuboCop::Cop::Base - Inherited

DEPARTMENT_SEVERITIES, EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

SYMBOL_TO_STRING_CACHE

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

  • .autocorrect_incompatible_with

    Style/StabbyLambdaParentheses wraps the parameter this cop removes in the same pass, which would leave an empty parameter list that forbids it.

::RuboCop::Cop::TargetRubyVersion - Extended

::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::ConfigurableEnforcedStyle - 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::ConfigurableEnforcedStyle - Included

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

Style/StabbyLambdaParentheses wraps the parameter this cop removes in the same pass, which would leave an empty parameter list that forbids it.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 68

def self.autocorrect_incompatible_with
  [Style::Lambda, Style::StabbyLambdaParentheses]
end

Instance Method Details

#block_variables(body, block_argument_name) (private)

[ GitHub ]

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

def block_variables(body, block_argument_name)
  body.each_descendant(:lvar).select do |descendant|
    descendant.source == block_argument_name
  end
end

#find_block_variables(node, block_argument_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 124

def find_block_variables(node, block_argument_name)
  return [] if !node.body || it_variable_in_scope?(node)

  ranges = inner_block_ranges(node.body)

  block_variables(node.body, block_argument_name).reject do |variable|
    ranges.any? { |range| range.contains?(variable.source_range) }
  end
end

#inner_block_ranges(body) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 167

def inner_block_ranges(body)
  body.each_node(:any_block).map { |block| block.loc.begin.join(block.loc.end) }
end

#it_argument_in_scope?(node, scope) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 154

def it_argument_in_scope?(node, scope)
  owners = node.each_ancestor(:block).select { |block| nearest_scope(block).equal?(scope) }
  owners << scope if scope&.any_def_type?

  owners.any? { |owner| owner.arguments.argument_list.any? { |arg| arg.name == :it } }
end

#it_variable_definitions (private)

[ GitHub ]

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

def it_variable_definitions
  @it_variable_definitions ||=
    variable_definitions(processed_source.ast).filter_map do |name, definition|
      definition if name == 'it'
    end
end

#it_variable_in_scope?(node) ⇒ Boolean (private)

[ GitHub ]

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

def it_variable_in_scope?(node)
  scope = nearest_scope(node)
  return true if it_argument_in_scope?(node, scope)

  it_variable_definitions.any? do |definition|
    nearest_scope(definition).equal?(scope) && visible_in_block?(definition, node)
  end
end

#keep_parameter_name?(body, block_arg_name) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 171

def keep_parameter_name?(body, block_arg_name)
  used_within_inner_block?(body, block_arg_name) || reassigned?(body, block_arg_name)
end

#nearest_scope(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 150

def nearest_scope(node)
  node.each_ancestor(*SCOPE_TYPES).first
end

#on_block(node)

[ GitHub ]

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

def on_block(node)
  return unless style == :always
  return unless node.arguments.one?

  # `restarg`, `kwrestarg`, `blockarg` nodes can return early.
  return unless node.first_argument.arg_type?

  block_argument_name = node.first_argument.source
  return if keep_parameter_name?(node.body, block_argument_name)

  find_block_variables(node, block_argument_name).each do |variable|
    add_offense(variable, message: MSG_USE_IT_PARAMETER) do |corrector|
      corrector.remove(node.arguments)
      corrector.replace(variable, 'it')
    end
  end
end

#on_itblock(node)

[ GitHub ]

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

def on_itblock(node)
  case style
  when :allow_single_line
    return if node.single_line?

    add_offense(node, message: MSG_AVOID_IT_PARAMETER_MULTILINE)
  when :disallow
    variables = find_block_variables(node, 'it')

    variables.each do |variable|
      add_offense(variable, message: MSG_AVOID_IT_PARAMETER)
    end
  end
end

#on_new_investigation

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 72

def on_new_investigation
  @it_variable_definitions = nil
end

#on_numblock(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 94

def on_numblock(node)
  return if style == :disallow
  return unless node.children[1] == 1

  variables = find_block_variables(node, '_1')

  variables.each do |variable|
    add_offense(variable, message: MSG_USE_IT_PARAMETER) do |corrector|
      corrector.replace(variable, 'it')
    end
  end
end

#reassigned?(body, block_argument_name) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 185

def reassigned?(body, block_argument_name)
  return false unless body

  variable_definitions(body).any? { |name, _definition| name == block_argument_name }
end

#used_within_inner_block?(body, block_argument_name) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 175

def used_within_inner_block?(body, block_argument_name)
  return false unless body

  ranges = inner_block_ranges(body)

  block_variables(body, block_argument_name).any? do |variable|
    ranges.any? { |range| range.contains?(variable.source_range) }
  end
end

#variable_definitions(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 197

def variable_definitions(node)
  node.each_node(:lvasgn, :match_var, :match_with_lvasgn).flat_map do |definition|
    names = if definition.match_with_lvasgn_type?
              definition.children.first.each_capture(named: true).map(&:name)
            else
              [definition.children.first.to_s]
            end

    names.map { |name| [name, definition] }
  end
end

#visible_in_block?(definition, node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/it_block_parameter.rb', line 161

def visible_in_block?(definition, node)
  return true if definition.source_range.begin_pos < node.source_range.begin_pos

  node.source_range.contains?(definition.source_range)
end