Class: Orthoses::ActiveRecord::Enum

Inherits:
Object
  • Object
show all
Defined in:
lib/orthoses/active_record/enum.rb

Overview

<= 6.1

def enum(definitions)

>= 7.0

def enum(name = nil, values = nil, **options)

Instance Method Summary collapse

Constructor Details

#initialize(loader) ⇒ Enum

Returns a new instance of Enum.



10
11
12
# File 'lib/orthoses/active_record/enum.rb', line 10

def initialize(loader)
  @loader = loader
end

Instance Method Details

#callObject



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
# File 'lib/orthoses/active_record/enum.rb', line 14

def call
  enum = CallTracer::Lazy.new
  store = enum.trace('ActiveRecord::Enum#enum') do
    @loader.call
  end

  enum.captures.each do |capture|
    base_name = Utils.module_name(capture.method.receiver) or next

    sig = "include #{base_name}::ActiveRecord_Enum_EnumMethods"
    if !store[base_name].body.include?(sig)
      store[base_name] << sig
    end

    if capture.argument[:definitions]
      # on rails 6
      definitions = capture.argument[:definitions].slice!(:_prefix, :_suffix, :_scopes, :_default)
      options = capture.argument[:definitions].transform_keys { |key| :"#{key[1..-1]}" }
      definitions.each { |name, values| _enum(store, base_name, name, values, **options) }
    else
      # on rails 7
      name = capture.argument[:name]
      values = capture.argument[:values]
      options = capture.argument[:options]
      if name
        # rails 7 style
        values, options = options, {} unless values
        _enum(store, base_name, name, values, **options)
      else
        # rails 6 style
        definitions = options.slice!(:_prefix, :_suffix, :_scopes, :_default)
        options.transform_keys! { |key| :"#{key[1..-1]}" }

        definitions.each { |name, values| _enum(store, base_name, name, values, **options) }
      end
    end
  end

  store
end