Class: Rubocop::Cop::FavorSprintf

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

Constant Summary collapse

ERROR_MESSAGE =
'Favor sprintf over String#%.'

Instance Attribute Summary

Attributes inherited from Cop

#correlations, #offences

Instance Method Summary collapse

Methods inherited from Cop

#add_offence, #has_report?, inherited, #initialize

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
# File 'lib/rubocop/cop/favor_sprintf.rb', line 8

def inspect(file, source, tokens, sexp)
  each(:binary, sexp) do |s|
    op1 = s[1]
    operator = s[2]
    op2 = s[3]

    # we care only about the % operator
    next unless matching?(operator, op1, op2)

    # FIXME implement reliable lineno extraction
    # we either have some string literal
    if op1[0] == :string_literal
      lineno_struct = s[1][1][1][2]
      lineno = lineno_struct.lineno if lineno_struct.respond_to?(:lineno)
    else
      # or some identifier
      lineno_struct = s[1][1][2]
      lineno = lineno_struct.lineno if lineno_struct.respond_to?(:lineno)
    end

    add_offence(
      :convention,
      lineno,
      ERROR_MESSAGE
    ) if lineno
  end
end