123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::HashEachMethods

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

Overview

Checks for uses of each_key and each_value Hash methods.

Note
If you have an array of two-element arrays, you can put parentheses around the block arguments to indicate that you’re not working with a hash, and suppress RuboCop offenses.

Examples:

# bad
hash.keys.each { |k| p k }
hash.each { |k, unused_value| p k }

# good
hash.each_key { |k| p k }

# bad
hash.values.each { |v| p v }
hash.each { |unused_key, v| p v }

# good
hash.each_value { |v| p v }

AllowedReceivers: ['execute']

# good
execute(sql).keys.each { |v| p v }
execute(sql).values.each { |v| p v }

Cop Safety Information:

  • This cop is unsafe because it cannot be guaranteed that the receiver is a Hash. The ::RuboCop::Cop::AllowedReceivers configuration can mitigate, but not fully resolve, this safety issue.

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

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::Lint::UnusedArgument - Included

::RuboCop::Cop::AllowedReceivers - 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,
#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 Method Details

#check_argument(variable) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 186

def check_argument(variable)
  return unless variable.block_argument?

  (@block_args ||= []).push(variable)
end

#check_unused_block_args(node, key, value)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 79

def check_unused_block_args(node, key, value)
  return if node.body.nil?

  value_unused = unused_block_arg_exist?(node, value)
  key_unused = unused_block_arg_exist?(node, key)
  return if value_unused && key_unused

  if value_unused
    message = message('each_key', node.method_name, value.source)
    unused_range = key.source_range.end.join(value.source_range.end)

    register_each_args_offense(node, message, 'each_key', unused_range)
  elsif key_unused
    message = message('each_value', node.method_name, key.source)
    unused_range = key.source_range.begin.join(value.source_range.begin)

    register_each_args_offense(node, message, 'each_value', unused_range)
  end
end

#correct_args(node, corrector) (private)

[ GitHub ]

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

def correct_args(node, corrector)
  args = node.parent.arguments
  name, = *args.children.find { |arg| used?(arg) }

  corrector.replace(args, "|#{name}|")
end

#correct_implicit(node, corrector, method_name) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 196

def correct_implicit(node, corrector, method_name)
  corrector.replace(node, method_name)
  correct_args(node, corrector)
end

#correct_key_value_each(node, corrector) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 201

def correct_key_value_each(node, corrector)
  receiver = node.receiver.receiver
  name = "each_#{node.receiver.method_name.to_s.chop}"
  return correct_implicit(node, corrector, name) unless receiver

  new_source = receiver.source + "#{node.loc.dot.source}#{name}"
  corrector.replace(node, new_source)
end

#each_arguments(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 51

def_node_matcher :each_arguments, <<~PATTERN
  (block (call _ :each)(args $_key $_value) ...)
PATTERN

#format_message(method_name, current) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 182

def format_message(method_name, current)
  format(MSG, prefer: "each_#{method_name[0..-2]}", current: current)
end

#handleable?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 108

def handleable?(node)
  return false if use_array_converter_method_as_preceding?(node)
  return false unless (root_receiver = root_receiver(node))
  return false if hash_mutated?(node, root_receiver)

  !root_receiver.literal? || root_receiver.hash_type?
end

#hash_mutated?(node, receiver)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 61

def_node_matcher :hash_mutated?, <<~PATTERN
  `(send %1 :[]= ...)
PATTERN

#kv_each(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 46

def_node_matcher :kv_each, <<~PATTERN
  ({block numblock} $(call (call _ ${:keys :values}) :each) ...)
PATTERN

#kv_each_with_block_pass(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 56

def_node_matcher :kv_each_with_block_pass, <<~PATTERN
  (call $(call _ ${:keys :values}) :each (block_pass (sym _)))
PATTERN

#kv_range(outer_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 217

def kv_range(outer_node)
  outer_node.receiver.loc.selector.join(outer_node.loc.selector)
end

#message(prefer, method_name, unused_code) (private)

[ GitHub ]

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

def message(prefer, method_name, unused_code)
  format(
    UNUSED_BLOCK_ARG_MSG, prefer: prefer, current: method_name, unused_code: unused_code
  )
end

#on_block(node) Also known as: #on_numblock

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 65

def on_block(node)
  return unless handleable?(node)

  kv_each(node) do |target, method|
    register_kv_offense(target, method) and return
  end

  return unless (key, value = each_arguments(node))

  check_unused_block_args(node, key, value)
end

#on_block_pass(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 100

def on_block_pass(node)
  kv_each_with_block_pass(node.parent) do |target, method|
    register_kv_with_block_pass_offense(node, target, method)
  end
end

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

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

alias on_numblock on_block

#register_each_args_offense(node, message, prefer, unused_range) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 145

def register_each_args_offense(node, message, prefer, unused_range)
  add_offense(node, message: message) do |corrector|
    corrector.replace(node.send_node.loc.selector, prefer)
    corrector.remove(unused_range)
  end
end

#register_kv_offense(target, method) (private)

[ GitHub ]

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

def register_kv_offense(target, method)
  return unless (parent_receiver = target.receiver.receiver)
  return if allowed_receiver?(parent_receiver)

  current = target.receiver.loc.selector.join(target.source_range.end).source

  add_offense(kv_range(target), message: format_message(method, current)) do |corrector|
    correct_key_value_each(target, corrector)
  end
end

#register_kv_with_block_pass_offense(node, target, method) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 152

def register_kv_with_block_pass_offense(node, target, method)
  return unless (parent_receiver = node.parent.receiver.receiver)
  return if allowed_receiver?(parent_receiver)

  range = target.loc.selector.join(node.parent.loc.selector.end)

  add_offense(range, message: format_message(method, range.source)) do |corrector|
    corrector.replace(range, "each_#{method[0..-2]}")
  end
end

#root_receiver(node) (private)

[ GitHub ]

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

def root_receiver(node)
  receiver = node.receiver
  if receiver&.receiver
    root_receiver(receiver)
  else
    receiver
  end
end

#unused_block_arg_exist?(node, block_arg) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 127

def unused_block_arg_exist?(node, block_arg)
  lvar_sources = node.body.each_descendant(:lvar).map(&:source)

  if block_arg.mlhs_type?
    block_arg.each_descendant(:arg, :restarg).all? do |block_arg|
      lvar_sources.none?(block_arg.source.delete_prefix('*'))
    end
  else
    lvar_sources.none?(block_arg.source.delete_prefix('*'))
  end
end

#use_array_converter_method_as_preceding?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_each_methods.rb', line 163

def use_array_converter_method_as_preceding?(node)
  return false unless (preceding_method = node.children.first.children.first)
  unless preceding_method.call_type? ||
         preceding_method.block_type? || preceding_method.numblock_type?
    return false
  end

  ARRAY_CONVERTER_METHODS.include?(preceding_method.method_name)
end

#used?(arg) ⇒ Boolean (private)

[ GitHub ]

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

def used?(arg)
  @block_args.find { |var| var.declaration_node.loc == arg.loc }.used?
end