Module: ActiveRecordStringEnum

Defined in:
lib/rails_string_enum/active_record_string_enum.rb

Instance Method Summary collapse

Instance Method Details

#string_enum(name, enums, scopes: false, i18n_scope: nil) ⇒ Object

product.rb string_enum :color, %w(red green yellow) page.rb string_enum :background, %w(red green), i18n_scope: ‘product.color’, scopes: { pluralize: true }



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rails_string_enum/active_record_string_enum.rb', line 8

def string_enum(name, enums, scopes: false, i18n_scope: nil)
  # create constant with all values
  # Product::COLORS # => ["red", "green", "yellow"]
  const_name_all_values = name.to_s.pluralize.upcase
  const_set const_name_all_values, enums.map(&:to_s)

  klass = self
  enums.each do |value|
    # Product::RED #=> "red"
    const_set value.to_s.upcase, value.to_s

    # def red?() color == 'red' end
    klass.send(:detect_enum_conflict!, name, "#{value}?")
    klass.class_eval <<-METHOD, __FILE__, __LINE__
      def #{value}?
        #{name} == #{value.to_s.upcase}
      end
    METHOD

    # def red!() update! color: :red end
    klass.send(:detect_enum_conflict!, name, "#{value}!")
    define_method("#{value}!") { update! name => value }

    if scopes
      # scope :only_red, -> { where color: 'red' }
      # scope :only_reds, -> { where color: 'red' } # if scopes: { pluralize: true }
      scope_name = scopes.try(:fetch, :pluralize, nil) ? "only_#{value.to_s.pluralize}" : "only_#{value}"
      klass.send(:detect_enum_conflict!, name, scope_name, true)
      klass.scope scope_name, -> { klass.where name => value }
    end
  end

  define_attr_i18n_method(self, name, i18n_scope)
  define_collection_i18n_method(self, name, i18n_scope)
  define_collection_i18n_method_for_value(self, name, i18n_scope)
end