Class: Rubocop::Cop::Style::HashSyntax

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/style/hash_syntax.rb

Overview

This cop checks hash literal syntax.

It can enforce either the use of the class hash rocket syntax or the use of the newer Ruby 1.9 syntax (when applicable).

A separate offence is registered for each problematic pair.

Constant Summary collapse

MSG_19 =
'Use the new Ruby 1.9 hash syntax.'
MSG_HASH_ROCKETS =
'Always use hash rockets in hashes.'

Constants inherited from Cop

Cop::OPERATOR_METHODS

Instance Attribute Summary

Attributes inherited from Cop

#config, #corrections, #offences, #processed_source

Instance Method Summary collapse

Methods inherited from Cop

#add_offence, all, #autocorrect?, #convention, #cop_config, cop_name, #cop_name, cop_type, #debug?, #ignore_node, inherited, #initialize, lint?, #message, rails?, style?, #support_autocorrect?, #warning

Constructor Details

This class inherits a constructor from Rubocop::Cop::Cop

Instance Method Details

#autocorrect(node) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rubocop/cop/style/hash_syntax.rb', line 52

def autocorrect(node)
  @corrections << lambda do |corrector|
    if cop_config['EnforcedStyle'] == 'ruby19'
      replacement = node.loc.expression.source[1..-1]
        .sub(/\s*=>\s*/, ': ')
    else
      replacement = ':' + node.loc.expression.source
        .sub(/:\s*/, ' => ')
    end
    corrector.replace(node.loc.expression, replacement)
  end
end

#hash_rockets_check(node) ⇒ Object



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

def hash_rockets_check(node)
  pairs = *node

  pairs.each do |pair|
    if pair.loc.operator && pair.loc.operator.is?(':')
      convention(pair,
                 pair.loc.expression.begin.join(pair.loc.operator),
                 MSG_HASH_ROCKETS)
    end
  end
end

#on_hash(node) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/rubocop/cop/style/hash_syntax.rb', line 16

def on_hash(node)
  case cop_config['EnforcedStyle']
  when 'ruby19' then ruby19_check(node)
  when 'hash_rockets' then hash_rockets_check(node)
  else fail 'Unknown HashSyntax style'
  end
end

#ruby19_check(node) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rubocop/cop/style/hash_syntax.rb', line 24

def ruby19_check(node)
  pairs = *node

  sym_indices = pairs.all? { |p| word_symbol_pair?(p) }

  if sym_indices
    pairs.each do |pair|
      if pair.loc.operator && pair.loc.operator.is?('=>')
        convention(pair,
                   pair.loc.expression.begin.join(pair.loc.operator),
                   MSG_19)
      end
    end
  end
end