Class: Rubocop::Cop::Indentation

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

Constant Summary collapse

ERROR_MESSAGE =
'Indent when as deep as case.'

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

#each_when(sexp, case_ix = -1,, &block) ⇒ Object

Does a depth first search for :when, yielding the index of the corresponding :case for each one.



33
34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/indentation.rb', line 33

def each_when(sexp, case_ix = -1, &block)
  if sexp[0] == :case
    @total_case_ix = (@total_case_ix || -1) + 1
    each_when(sexp[2], @total_case_ix, &block)
  else
    yield case_ix if sexp[0] == :when
    sexp.grep(Array).each { |s| each_when(s, case_ix, &block) }
  end
end

#find_keywords(tokens, keyword) ⇒ Object



19
20
21
22
23
24
# File 'lib/rubocop/cop/indentation.rb', line 19

def find_keywords(tokens, keyword)
  indexes = tokens.each_index.select do |ix|
    keyword?(tokens, ix, keyword)
  end
  tokens.values_at(*indexes)
end

#inspect(file, source, tokens, sexp) ⇒ Object



8
9
10
11
12
13
14
15
16
17
# File 'lib/rubocop/cop/indentation.rb', line 8

def inspect(file, source, tokens, sexp)
  case_tokens = find_keywords(tokens, 'case')
  when_tokens = find_keywords(tokens, 'when')
  each_when(sexp) do |case_ix|
    when_pos = when_tokens.shift.pos
    if when_pos.column != case_tokens[case_ix].pos.column
      add_offence(:convention, when_pos.lineno, ERROR_MESSAGE)
    end
  end
end

#keyword?(tokens, ix, keyword) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
# File 'lib/rubocop/cop/indentation.rb', line 26

def keyword?(tokens, ix, keyword)
  [tokens[ix].type, tokens[ix].text] == [:on_kw, keyword] &&
    tokens[ix - 1].type != :on_symbeg
end