Class: RuboCop::Cop::Sevencop::HashElementOrdered

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

Overview

Sort Hash elements by key.

Examples:


# bad
{
  b: 1,
  a: 1,
  c: 1
}

# good
{
  a: 1,
  b: 1,
  c: 1
}

Constant Summary collapse

MSG =
'Sort Hash elements by key.'

Instance Method Summary collapse

Instance Method Details

#hash_literal?(node) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/rubocop/cop/sevencop/hash_element_ordered.rb', line 30

def_node_matcher :hash_literal?, <<~PATTERN
  (hash
    (pair
      {sym | str}
      _
    )+
  )
PATTERN

#on_hash(node) ⇒ Object

Parameters:

  • node (RuboCop::AST::HashNode)


40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rubocop/cop/sevencop/hash_element_ordered.rb', line 40

def on_hash(node)
  return unless hash_literal?(node)

  return if sorted?(node)

  add_offense(node) do |corrector|
    corrector.replace(
      node,
      autocorrect(node)
    )
  end
end