Module: Enumerize::ActiveRecordSupport

Defined in:
lib/enumerize/activerecord.rb

Defined Under Namespace

Modules: InstanceMethods, RelationMethods Classes: Type

Instance Method Summary collapse

Instance Method Details

#enumerize(name, options = {}) ⇒ Object


5
6
7
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
# File 'lib/enumerize/activerecord.rb', line 5

def enumerize(name, options={})
  super

  _enumerize_module.dependent_eval do
    if self < ::ActiveRecord::Base
      include InstanceMethods

      const_get(:ActiveRecord_Relation).include(RelationMethods)
      const_get(:ActiveRecord_AssociationRelation).include(RelationMethods)
      const_get(:ActiveRecord_Associations_CollectionProxy).include(RelationMethods)

      # Since Rails use `allocate` method on models and initializes them with `init_with` method.
      # This way `initialize` method is not being called, but `after_initialize` callback always gets triggered.
      after_initialize :_set_default_value_for_enumerized_attributes

      # https://github.com/brainspec/enumerize/issues/111
      require 'enumerize/hooks/uniqueness'

      unless options[:multiple]
        if ::ActiveRecord.version >= ::Gem::Version.new("6.1.0.alpha")
          decorate_attribute_type(name.to_s) do |subtype|
            Type.new(enumerized_attributes[name], subtype)
          end
        else
          decorate_attribute_type(name, :enumerize) do |subtype|
            Type.new(enumerized_attributes[name], subtype)
          end
        end
      end
    end
  end
end