Module: LegacyEnum::ClassMethods

Defined in:
lib/legacy_enum/class_methods.rb

Instance Method Summary collapse

Instance Method Details

#enum_idsObject

Returns all enumerations for the class by enum_name and then value => name



73
74
75
# File 'lib/legacy_enum/class_methods.rb', line 73

def enum_ids
  inject_block(:value, :name)
end

#enumsObject

Returns all enumerations for the class by enum_name and then name => value



63
64
65
# File 'lib/legacy_enum/class_methods.rb', line 63

def enums
  inject_block(:name, :value)
end

#labelsObject

Returns all enumerations for the class by enum_name and then name => label



68
69
70
# File 'lib/legacy_enum/class_methods.rb', line 68

def labels
  inject_block(:name, :label)
end

#legacy_enum(name, *options, &block) ⇒ Object



3
4
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/legacy_enum/class_methods.rb', line 3

def legacy_enum(name, *options, &block)
  extracted_options = options.extract_options!
  id_attr_name = extracted_options[:lookup].try(:to_s) || "#{name.to_s.capitalize}ID"

  config = MethodDefinitionDSL.new
  config.instance_eval(&block)

  cattr_accessor :enum_config unless defined? self.enum_config
  self.enum_config ||= {}

  self.enum_config[name] = { values: config.enum_def, lookup: id_attr_name }

  class_eval do

    define_method "#{name}_changed?" do
      send "#{id_attr_name}_changed?"
    end

    define_method name do
      enum_config[name][:values].valued(legacy_value(name))[:name]
    end

    define_method "#{name}=" do |value|
      normalized_value = value.nil? ? value : value.to_sym
      set_value = enum_config[name][:values].named(normalized_value)[:value]
      set_legacy_value name, set_value
    end

    define_method "#{name}_label" do
      enum_config[name][:values].valued(legacy_value(name))[:label]
    end

    def legacy_value(name)
      send enum_config[name][:lookup].to_sym
    end

    def set_legacy_value(name, value)
      send "#{enum_config[name][:lookup]}=".to_sym, value
    end

    return unless extracted_options[:scope]

    scope name.to_sym,
      lambda { |enum_value| where(id_attr_name => enum_config[name][:values].named(enum_value)[:value] ) }

    enum_config[name][:values].each do |config|
      singleton_class.instance_eval do
        if extracted_options[:scope] == :one
          define_method config[:name].to_sym, lambda { send(name, config[:name]).first }
        else
          define_method config[:name].to_sym, lambda { send(name, config[:name]) }
        end
      end
    end

  end

end