Class: Rubocop::Cop::Style::HashSyntax
- 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
Instance Attribute Summary
Attributes inherited from Cop
#config, #corrections, #offences, #processed_source
Instance Method Summary collapse
- #autocorrect(node) ⇒ Object
- #hash_rockets_check(node) ⇒ Object
- #on_hash(node) ⇒ Object
- #ruby19_check(node) ⇒ Object
Methods inherited from Cop
#add_offence, all, #autocorrect?, #convention, #cop_config, cop_name, #cop_name, cop_type, #debug?, #ignore_node, inherited, #initialize, lint?, #message, non_rails, rails?, style?, #support_autocorrect?, #warning
Constructor Details
This class inherits a constructor from Rubocop::Cop::Cop
Instance Method Details
#autocorrect(node) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/rubocop/cop/style/hash_syntax.rb', line 38 def autocorrect(node) key = node.children.first.loc.expression op = node.loc.operator if cop_config['EnforcedStyle'] == 'ruby19' && !space_before_operator?(op, key) && config.for_cop('SpaceAroundOperators')['Enabled'] # Don't do the correction if there is no space before '=>'. The # combined corrections of this cop and SpaceAroundOperators could # produce code with illegal syntax. fail CorrectionNotPossible end @corrections << lambda do |corrector| if cop_config['EnforcedStyle'] == 'ruby19' corrector.insert_after(key, ' ') corrector.replace(key, key.source.sub(/^:(.*)/, '\1:')) else corrector.insert_after(key, ' => ') corrector.insert_before(key, ':') end corrector.remove(range_with_surrounding_space(op)) end end |
#hash_rockets_check(node) ⇒ Object
32 33 34 35 36 |
# File 'lib/rubocop/cop/style/hash_syntax.rb', line 32 def hash_rockets_check(node) pairs = *node check(pairs, ':', MSG_HASH_ROCKETS) 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 |
# 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) } check(pairs, '=>', MSG_19) if sym_indices end |