Class: RuboCop::Cop::Ipepe::AlphabeticalArrayOfStrings

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/ipepe/alphabetical_array_of_strings.rb

Constant Summary collapse

MSG =
"Ensure that strings in array are in alphabetical order".freeze

Instance Method Summary collapse

Instance Method Details

#on_array(node) ⇒ Object



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

def on_array(node)
  str_type_hash = {}
  node.children.each do |n|
    str_type_hash[n.str_type?] ||= 0
    str_type_hash[n.str_type?] += 1
  end

  return if str_type_hash.size != 1 || str_type_hash[true].nil?

  strings = node.children.map(&:value)
  sorted_strings = strings.sort

  return if strings == sorted_strings

  add_offense(node) do |corrector|
    corrector.replace(node, "[#{sorted_strings.map { |s| "\"#{s}\"" }.join(', ')}]")
  end
end