Class: Rubocop::Cop::SingleLineMethods

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

Constant Summary collapse

ERROR_MESSAGE =
'Avoid single-line methods.'

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/single_line_methods.rb', line 8

def inspect(file, source, tokens, sexp)
  if SingleLineMethods.config['AllowIfMethodIsEmpty']
    is_empty = empty_methods(sexp)
  end

  lineno_of_def = nil
  possible_offence = false

  tokens.each_with_index do |token, ix|
    if possible_offence
      if token.pos.lineno > lineno_of_def
        possible_offence = false
      elsif [token.type, token.text] == [:on_kw, 'end']
        add_offence(:convention, lineno_of_def, ERROR_MESSAGE)
      end
    end

    if [token.type, token.text] == [:on_kw, 'def']
      lineno_of_def = token.pos.lineno
      name_token = tokens[ix..-1].find do |t|
        [:on_ident, :on_const].include?(t.type)
      end
      possible_offence =
        if SingleLineMethods.config['AllowIfMethodIsEmpty']
          !is_empty[name_token.pos]
        else
          true
        end
    end
  end
end