Module: EnumMachine::DriverSimpleClass

Defined in:
lib/enum_machine/driver_simple_class.rb

Class Method Summary collapse

Class Method Details

.call(args) ⇒ Object

include EnumMachine[

state: { enum: %w[choice in_delivery], i18n_scope: 'line_item.state' },
color: { enum: %w[red green yellow] },
type:  { enum: %w[CartType BookmarkType] },

]



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
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/enum_machine/driver_simple_class.rb', line 11

def self.call(args)
  Module.new do
    define_singleton_method(:included) do |klass|
      args.each do |attr, params|
        enum_values  = params.fetch(:enum)
        i18n_scope   = params.fetch(:i18n_scope, nil)

        if defined?(ActiveRecord) && klass <= ActiveRecord::Base
          klass.enum_machine(attr, enum_values, i18n_scope: i18n_scope)
        else
          enum_const_name = attr.to_s.upcase
          enum_klass = BuildClass.call(enum_values: enum_values, i18n_scope: i18n_scope)

          enum_value_klass = BuildAttribute.call(enum_values: enum_values, i18n_scope: i18n_scope)
          enum_klass.const_set :VALUE_KLASS, enum_value_klass

          value_attribute_mapping = enum_values.to_h { |enum_value| [enum_value, enum_klass::VALUE_KLASS.new(enum_value).freeze] }

          define_methods =
            Module.new do
              define_method(attr) do
                enum_value = super()
                return unless enum_value

                value_attribute_mapping.fetch(enum_value)
              end
            end

          enum_decorator =
            Module.new do
              define_singleton_method(:included) do |decorating_klass|
                decorating_klass.prepend define_methods
                decorating_klass.const_set enum_const_name, enum_klass
              end
            end
          enum_klass.define_singleton_method(:decorator_module) { enum_decorator }

          klass.include(enum_decorator)
          enum_decorator
        end
      end
    end
  end
end