Class: Rubocop::Cop::WordArray

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

Constant Summary collapse

ERROR_MESSAGE =
'Use %w or %W for array of words.'

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

#complex_content?(arr_sexp) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rubocop/cop/word_array.rb', line 25

def complex_content?(arr_sexp)
  non_empty_strings = 0

  each(:@tstring_content, arr_sexp) do |content|
    non_empty_strings += 1
    return true unless content[1] =~ /\A[\w-]+\z/
  end

  # check for '' strings in the array
  non_empty_strings == arr_sexp.size ? false : true
end

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



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/rubocop/cop/word_array.rb', line 8

def inspect(file, source, tokens, sexp)
  each(:array, sexp) do |s|
    array_elems = s[1]

    # no need to check empty arrays
    next unless array_elems && array_elems.size > 1

    string_array = array_elems.all? { |e| e[0] == :string_literal }

    if string_array && !complex_content?(array_elems)
      add_offence(:convention,
                  all_positions(s).first.lineno,
                  ERROR_MESSAGE)
    end
  end
end