Class: Rubocop::Cop::HashLiteral
- Defined in:
- lib/rubocop/cop/hash_literal.rb
Constant Summary collapse
- ERROR_MESSAGE =
'Use hash literal {} instead of Hash.new.'
Instance Attribute Summary
Attributes inherited from Cop
#correlations, #debug, #disabled_lines, #offences
Instance Method Summary collapse
Methods inherited from Cop
#add_offence, cop_name, #has_report?, inherited, #initialize, #name
Constructor Details
This class inherits a constructor from Rubocop::Cop::Cop
Instance Method Details
#inspect(file, source, tokens, sexp) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/rubocop/cop/hash_literal.rb', line 8 def inspect(file, source, tokens, sexp) offences = preliminary_scan(sexp) # find Hash.new() each(:method_add_arg, sexp) do |s| next if s[1][0] != :call receiver = s[1][1][1] method_name = s[1][3][1] if receiver && receiver[1] == 'Hash' && method_name == 'new' && s[2] == [:arg_paren, nil] offences.delete(Offence.new(:convention, receiver[2].lineno, ERROR_MESSAGE)) add_offence(:convention, receiver[2].lineno, ERROR_MESSAGE) end # check for false positives if receiver && receiver[1] == 'Hash' && method_name == 'new' && s[2] != [:arg_paren, nil] offences.delete(Offence.new(:convention, receiver[2].lineno, ERROR_MESSAGE)) end end offences.each { |o| add_offence(*o.explode) } end |
#preliminary_scan(sexp) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/rubocop/cop/hash_literal.rb', line 40 def preliminary_scan(sexp) offences = [] # find Hash.new # there will be some false positives here, which # we'll eliminate later on each(:call, sexp) do |s| receiver = s[1][1] if receiver && receiver[1] == 'Hash' && s[3][1] == 'new' offences << Offence.new(:convention, receiver[2].lineno, ERROR_MESSAGE) end end offences end |