Module: RuboCop::Cop::HashShorthandSyntax

Included in:
Style::HashSyntax
Defined in:
lib/rubocop/cop/mixin/hash_shorthand_syntax.rb

Overview

This module checks for Ruby 3.1’s hash value omission syntax.

Constant Summary collapse

OMIT_HASH_VALUE_MSG =
'Omit the hash value.'
EXPLICIT_HASH_VALUE_MSG =
'Explicit the hash value.'

Instance Method Summary collapse

Instance Method Details

#on_pair(node) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rubocop/cop/mixin/hash_shorthand_syntax.rb', line 10

def on_pair(node)
  return if ignore_hash_shorthand_syntax?(node)

  hash_key_source = node.key.source

  if enforced_shorthand_syntax == 'always'
    return if node.value_omission? || require_hash_value?(hash_key_source, node)

    message = OMIT_HASH_VALUE_MSG
    replacement = "#{hash_key_source}:"
  else
    return unless node.value_omission?

    message = EXPLICIT_HASH_VALUE_MSG
    replacement = "#{hash_key_source}: #{hash_key_source}"
  end

  add_offense(node.value, message: message) do |corrector|
    corrector.replace(node, replacement)
  end
end