Module: Foobara::Enumerated::Accessors::ClassMethods

Defined in:
foobara-0.0.110/projects/enumerated/src/accessors.rb

Instance Method Summary collapse

Instance Method Details

#enumerated(attribute_name, values_source = nil) ⇒ Object



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
# File 'foobara-0.0.110/projects/enumerated/src/accessors.rb', line 10

def enumerated(attribute_name, values_source = nil)
  original_values_source = values_source

  if values_source.nil?
    module_name = Util.classify(attribute_name)

    values_source = begin
      Util.const_get_up_hierarchy(self, module_name)
    rescue NameError
      # :nocov:
      raise CannotDetermineModuleAutomatically,
            "could not find a module for #{module_name}. Maybe consider passing it in explicitly."
      # :nocov:
    end
  end

  values = Values.new(values_source)

  attribute_name = attribute_name.to_sym

  # :nocov:
  unless respond_to?(:enumerated_type_metadata)
    # :nocov:
    class << self
      attr_accessor :enumerated_type_metadata
    end

    self. = {}
  end

  attr_reader attribute_name

  define_method "#{attribute_name}=" do |value|
    value = Values.normalize_value(value)

    if !value.nil? && !values.all_values.include?(value)
      raise ValueNotAllowed, "Received #{value} for #{attribute_name} but expected one of #{values.all_values}"
    end

    instance_variable_set("@#{attribute_name}", value)
  end

  [attribute_name] = {
    original_values_source:,
    values_source:,
    values:
  }
end