Class: RuboCop::Cop::Sorted::SortHashKeys

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/sorted/sort_hash_keys.rb

Overview

Checks that the keys of a hash are sorted alphabetically when enabled. The configuration option VariableNamesToCheck can be set to an array of strings. Only hashes assigned to variables matching the supplied names will be inspected. By default, this option is not set.

# bad
hash = {
z: 1,
a: 2
}

# good
hash = {
a: 2,
z: 1
}

Constant Summary collapse

MSG =
'Key is not sorted alphabetically'

Instance Method Summary collapse

Instance Method Details

#on_hash(node) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/rubocop/cop/sorted/sort_hash_keys.rb', line 28

def on_hash(node)
  @node = node

  return if targeted_investigation? && !variable_of_interest?

  return if hash_keys.map(&method(:str_from)) == sorted_key_strings

  add_offense_to_keys
  add_offense_to_hash
end