class RuboCop::Cop::Rails::EnumHash
This cop looks for enums written with array syntax.
When using array syntax, adding an element in a position other than the last causes all previous definitions to shift. Explicitly specifying the value for each key prevents this from happening.
@example
# bad enum status: [:active, :archived] # good enum status: { active: 0, archived: 1 }
Constants
- MSG
- RESTRICT_ON_SEND
Public Instance Methods
on_send(node)
click to toggle source
# File lib/rubocop/cop/rails/enum_hash.rb, line 35 def on_send(node) enum?(node) do |pairs| pairs.each do |pair| key, array = array_pair?(pair) next unless key add_offense(array, message: format(MSG, enum: enum_name(key))) do |corrector| hash = array.children.each_with_index.map do |elem, index| "#{source(elem)} => #{index}" end.join(', ') corrector.replace(array.loc.expression, "{#{hash}}") end end end end
Private Instance Methods
enum_name(key)
click to toggle source
# File lib/rubocop/cop/rails/enum_hash.rb, line 54 def enum_name(key) case key.type when :sym, :str key.value else key.source end end
source(elem)
click to toggle source
# File lib/rubocop/cop/rails/enum_hash.rb, line 63 def source(elem) case elem.type when :str elem.value.dump when :sym elem.value.inspect else elem.source end end