Class: RuboCop::Cop::DevDoc::Rails::EnumMustBeSymbolized

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/dev_doc/rails/enum_must_be_symbolized.rb

Overview

Every Rails enum declaration must be paired with enum_symbolize so the reader returns a symbol instead of Rails' default string form.

Rationale

Strings and symbols are not equal in Ruby (:foo == 'foo' is false). Rails' enum macro defines a reader that returns the string form, so downstream comparisons like record.status == :active silently fail. Pairing enum :status, … with enum_symbolize :status overrides the reader to hand back a symbol, eliminating the footgun.

See best_practices/backend/en/01a_defensive_programming.md item 7.


class Order < ApplicationRecord
enum :payment_status, { draft: 0, pending: 1, finalized: 2 }
end


class Order < ApplicationRecord
enum :payment_status, { draft: 0, pending: 1, finalized: 2 }

enum_symbolize :payment_status
end

enum_symbolize accepts multiple names so several enums can be paired in one call:


enum_symbolize :payment_status, :finalize_intent

Enums declared inside a concern's included do block are checked the same way — the pairing must live in the same included do block, which is also where it belongs so every includer gets both:


included do
enum :discount_type, DISCOUNT_TYPES
enum_symbolize :discount_type
end

Examples:

# bad
enum :status, { active: 0, archived: 1 }

# good
enum :status, { active: 0, archived: 1 }
enum_symbolize :status

Constant Summary collapse

MSG =
'Pair `enum :%<name>s` with `enum_symbolize :%<name>s` so the reader returns a symbol ' \
'(see backend/01a_defensive_programming.md item 7).'.freeze

Instance Method Summary collapse

Instance Method Details

#on_block(node) ⇒ Object

Concern-declared enums: included do ... end runs in the including class's context, so its statements are checked like a class body.



74
75
76
77
78
# File 'lib/rubocop/cop/dev_doc/rails/enum_must_be_symbolized.rb', line 74

def on_block(node)
  return unless included_block?(node)

  check_body(node.body)
end

#on_class(node) ⇒ Object



68
69
70
# File 'lib/rubocop/cop/dev_doc/rails/enum_must_be_symbolized.rb', line 68

def on_class(node)
  check_body(node.body)
end