Class: RuboCop::Cop::Rails::EnumStartingValue
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Rails::EnumStartingValue
- Defined in:
- lib/rubocop/cop/rails/enum_starting_value.rb
Overview
Prevent the user to start from Zero with an enum. When using a wrong value like .where(state: :patato) let Rails + MySQL do a WHERE state = 0. It will match nothing since no record will have a 0 value.
# bad
enum my_enum: {apple: 0, bannana: 1}
# good
enum my_enum: {apple: 1, banana: 2}
Constant Summary collapse
- MSG =
'Prefer starting from `1` instead of `0` with `enum`.'
Instance Method Summary collapse
Instance Method Details
#on_send(node) ⇒ Object
27 28 29 30 31 |
# File 'lib/rubocop/cop/rails/enum_starting_value.rb', line 27 def on_send(node) return unless enum? node add_offense(node) if start_with_zero?(enum_attributes(node)) end |
#start_with_zero?(node) ⇒ Boolean
33 34 35 36 37 38 39 40 |
# File 'lib/rubocop/cop/rails/enum_starting_value.rb', line 33 def start_with_zero?(node) return false unless node.type == :hash node.children.any? do |child| value = child.value value.type == :int && value.value.zero? end end |