class RuboCop::Cop::Style::PreferredHashMethods

Checks for uses of methods ‘Hash#has_key?` and `Hash#has_value?`, and suggests using `Hash#key?` and `Hash#value?` instead.

It is configurable to enforce the verbose method names, by using the ‘EnforcedStyle: verbose` configuration.

@safety

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

@example EnforcedStyle: short (default)

# bad
Hash#has_key?
Hash#has_value?

# good
Hash#key?
Hash#value?

@example EnforcedStyle: verbose

# bad
Hash#key?
Hash#value?

# good
Hash#has_key?
Hash#has_value?

Constants

MSG
OFFENDING_SELECTORS
RESTRICT_ON_SEND

Public Instance Methods

on_csend(node)
Alias for: on_send
on_send(node) click to toggle source
# File lib/rubocop/cop/style/preferred_hash_methods.rb, line 43
def on_send(node)
  return unless node.arguments.one? && offending_selector?(node.method_name)

  message = message(node.method_name)

  add_offense(node.loc.selector, message: message) do |corrector|
    corrector.replace(node.loc.selector, proper_method_name(node.loc.selector.source))
  end
end
Also aliased as: on_csend

Private Instance Methods

message(method_name) click to toggle source
# File lib/rubocop/cop/style/preferred_hash_methods.rb, line 56
def message(method_name)
  format(MSG, prefer: proper_method_name(method_name), current: method_name)
end
offending_selector?(method_name) click to toggle source
# File lib/rubocop/cop/style/preferred_hash_methods.rb, line 68
def offending_selector?(method_name)
  OFFENDING_SELECTORS[style].include?(method_name)
end
proper_method_name(method_name) click to toggle source
# File lib/rubocop/cop/style/preferred_hash_methods.rb, line 60
def proper_method_name(method_name)
  if style == :verbose
    "has_#{method_name}"
  else
    method_name.to_s.delete_prefix('has_')
  end
end