Class: Rubocop::Cop::WhenThen

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

Constant Summary collapse

ERROR_MESSAGE =
'Never use "when x;". Use "when x then" instead.'

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

def inspect(file, source, tokens, sexp)
  each(:when, sexp) do |s|
    # The grammar is:
    # when <value> <divider> <body>
    # where divider is either semicolon, then, or line break.
    last_pos_in_value = all_positions(s[1])[-1]
    start_index = tokens.index { |t| t.pos == last_pos_in_value }
    tokens[start_index..-1].each do |t|
      break if ['then', "\n"].include?(t.text)
      if t.type == :on_semicolon
        add_offence(:convention, t.pos.lineno, ERROR_MESSAGE)
      end
    end
  end
end