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. rubocop:disable Metrics/ModuleLength

Defined Under Namespace

Classes: DefNode

Constant Summary collapse

OMIT_HASH_VALUE_MSG =
'Omit the hash value.'
EXPLICIT_HASH_VALUE_MSG =
'Include the hash value.'
DO_NOT_MIX_MSG_PREFIX =
'Do not mix explicit and implicit hash values.'
DO_NOT_MIX_OMIT_VALUE_MSG =
"#{DO_NOT_MIX_MSG_PREFIX} #{OMIT_HASH_VALUE_MSG}"
DO_NOT_MIX_EXPLICIT_VALUE_MSG =
"#{DO_NOT_MIX_MSG_PREFIX} #{EXPLICIT_HASH_VALUE_MSG}"
KEYWORDS =

A keyword parameter can be named after a keyword, as in def foo(if:), but the parameter can only be referenced by an omitted hash value, so { if: } has no explicit form: { if: if } is invalid Ruby.

%i[
  __ENCODING__ __FILE__ __LINE__ BEGIN END alias and begin break case class def do
  else elsif end ensure false for if in module next nil not or redo rescue retry
  return self super then true undef unless until when while yield
].to_set.freeze

Instance Method Summary collapse

Instance Method Details

#on_hash_for_mixed_shorthand(hash_node) ⇒ Object



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

def on_hash_for_mixed_shorthand(hash_node)
  return if ignore_mixed_hash_shorthand_syntax?(hash_node)

  hash_value_type_breakdown = breakdown_value_types_of_hash(hash_node)

  if hash_with_mixed_shorthand_syntax?(hash_value_type_breakdown)
    mixed_shorthand_syntax_check(hash_value_type_breakdown)
  else
    no_mixed_shorthand_syntax_check(hash_value_type_breakdown)
  end
end

#on_pair(node) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rubocop/cop/mixin/hash_shorthand_syntax.rb', line 53

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}:"
    self.config_to_allow_offenses = { 'Enabled' => false }
  else
    return if !node.value_omission? || keyword_value?(node)

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

  register_offense(node, message, replacement)
end