123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::HashExcept

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

Overview

Checks for usages of Hash#reject, Hash#select, and Hash#filter methods that can be replaced with Hash#except method.

This cop should only be enabled on Ruby version 3.0 or higher. (Hash#except was added in Ruby 3.0.)

For safe detection, it is limited to commonly used string and symbol comparisons when used ==. And do not check Hash#delete_if and Hash#keep_if to change receiver object.

Examples:

# bad
{foo: 1, bar: 2, baz: 3}.reject {|k, v| k == :bar }
{foo: 1, bar: 2, baz: 3}.select {|k, v| k != :bar }
{foo: 1, bar: 2, baz: 3}.filter {|k, v| k != :bar }
{foo: 1, bar: 2, baz: 3}.reject {|k, v| k.eql?(:bar) }

# bad
{foo: 1, bar: 2, baz: 3}.reject {|k, v| %i[bar].include?(k) }
{foo: 1, bar: 2, baz: 3}.select {|k, v| !%i[bar].include?(k) }
{foo: 1, bar: 2, baz: 3}.filter {|k, v| !%i[bar].include?(k) }

# bad
{foo: 1, bar: 2, baz: 3}.reject {|k, v| !%i[bar].exclude?(k) }
{foo: 1, bar: 2, baz: 3}.select {|k, v| %i[bar].exclude?(k) }

# bad
{foo: 1, bar: 2, baz: 3}.reject {|k, v| k.in?(%i[bar]) }
{foo: 1, bar: 2, baz: 3}.select {|k, v| !k.in?(%i[bar]) }

# good
{foo: 1, bar: 2, baz: 3}.except(:bar)

Cop Safety Information:

  • This cop is unsafe because it cannot be guaranteed that the receiver is a Hash or responds to the replacement method.

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

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

Instance Method Details

#bad_method?(block) ⇒ Boolean (private)

Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_except.rb', line 105

def bad_method?(block)
  if active_support_extensions_enabled?
    bad_method_with_active_support?(block) do |key_arg, send_node|
      if send_node.method?(:in?) && send_node.receiver&.source != key_arg.source
        return false
      end
      return true if !send_node.method?(:include?) && !send_node.method?(:exclude?)

      send_node.first_argument&.source == key_arg.source
    end
  else
    bad_method_with_poro?(block) do |key_arg, send_node|
      !send_node.method?(:include?) || send_node.first_argument&.source == key_arg.source
    end
  end
end

#bad_method_with_active_support?(node)

[ GitHub ]

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

def_node_matcher :bad_method_with_active_support?, <<~PATTERN
  (block
    (send _ _)
    (args
      $(arg _)
      (arg _))
    {
      $(send
        _ {:== :!= :eql? :in? :include? :exclude?} _)
      (send
        $(send
          _ {:== :!= :eql? :in? :include? :exclude?} _) :!)
      })
PATTERN

#bad_method_with_poro?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_except.rb', line 55

def_node_matcher :bad_method_with_poro?, <<~PATTERN
  (block
    (call _ _)
    (args
      $(arg _)
      (arg _))
    {
      $(send
        _ {:== :!= :eql? :include?} _)
      (send
        $(send
          _ {:== :!= :eql? :include?} _) :!)
      })
PATTERN

#decorate_source(value) (private)

[ GitHub ]

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

def decorate_source(value)
  return ":\"#{value.source}\"" if value.dsym_type?
  return "\"#{value.source}\"" if value.dstr_type?
  return ":#{value.source}" if value.sym_type?

  "'#{value.source}'"
end

#except_key(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_except.rb', line 189

def except_key(node)
  key_argument = node.argument_list.first.source
  body = extract_body_if_negated(node.body)
  lhs, _method_name, rhs = *body
  return if [lhs, rhs].map(&:source).none?(key_argument)

  [lhs, rhs].find { |operand| operand.source != key_argument }
end

#except_key_source(key) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_except.rb', line 168

def except_key_source(key)
  if key.array_type?
    key = if key.percent_literal?
            key.each_value.map { |v| decorate_source(v) }
          else
            key.each_value.map(&:source)
          end
    return key.join(', ')
  end

  key.literal? ? key.source : "*#{key.source}"
end

#extract_body_if_negated(body) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_except.rb', line 162

def extract_body_if_negated(body)
  return body unless body.method?('!')

  body.receiver
end

#included?(negated, body) ⇒ Boolean (private)

[ GitHub ]

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

def included?(negated, body)
  if negated
    body.method?('exclude?')
  else
    body.method?('include?') || body.method?('in?')
  end
end

#not_included?(negated, body) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_except.rb', line 147

def not_included?(negated, body)
  included?(!negated, body)
end

#offense_range(node) (private)

[ GitHub ]

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

def offense_range(node)
  range_between(node.loc.selector.begin_pos, node.parent.loc.end.end_pos)
end

#on_csend(node)

Alias for #on_send.

[ GitHub ]

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

alias on_csend on_send

#on_send(node) Also known as: #on_csend

[ GitHub ]

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

def on_send(node)
  block = node.parent
  return unless bad_method?(block) && semantically_except_method?(node, block)

  except_key = except_key(block)
  return if except_key.nil? || !safe_to_register_offense?(block, except_key)

  range = offense_range(node)
  preferred_method = "except(#{except_key_source(except_key)})"

  add_offense(range, message: format(MSG, prefer: preferred_method)) do |corrector|
    corrector.replace(range, preferred_method)
  end
end

#safe_to_register_offense?(block, except_key) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_except.rb', line 151

def safe_to_register_offense?(block, except_key)
  extracted = extract_body_if_negated(block.body)
  if extracted.method?('in?') || extracted.method?('include?') ||
     extracted.method?('exclude?')
    return true
  end
  return true if block.body.method?('eql?')

  except_key.sym_type? || except_key.str_type?
end

#semantically_except_method?(send, block) ⇒ Boolean (private)

Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity

[ GitHub ]

  
# File 'lib/rubocop/cop/style/hash_except.rb', line 123

def semantically_except_method?(send, block)
  body = block.body

  negated = body.method?('!')
  body = body.receiver if negated

  case send.method_name
  when :reject
    body.method?('==') || body.method?('eql?') || included?(negated, body)
  when :select, :filter
    body.method?('!=') || not_included?(negated, body)
  else
    false
  end
end