Module: Vets::Attributes::ClassMethods

Defined in:
lib/vets/attributes.rb

Instance Method Summary collapse

Instance Method Details

#attribute(name, klass, **options) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/vets/attributes.rb', line 16

def attribute(name, klass, **options)
  default = options[:default]
  array = options[:array] || false

  attributes[name] = { type: klass, default:, array: }

  define_getter(name, default)
  define_setter(name, klass, array)
end

#attribute_setObject



26
27
28
29
# File 'lib/vets/attributes.rb', line 26

def attribute_set
  # grabs attribute keys from parent classes
  ancestors.select { |klass| klass.respond_to?(:attributes) }.flat_map { |klass| klass.attributes.keys }.uniq
end

#attributesObject



12
13
14
# File 'lib/vets/attributes.rb', line 12

def attributes
  @attributes ||= {} # rubocop:disable ThreadSafety/InstanceVariableInClassMethod
end

#define_getter(name, default) ⇒ Object (private)



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/vets/attributes.rb', line 33

def define_getter(name, default)
  define_method(name) do
    instance_variable_get("@#{name}") || begin
      return nil unless defined?(default)

      if default.is_a?(Symbol) && respond_to?(default)
        send(default)
      else
        default
      end
    end
  end
end

#define_setter(name, klass, array) ⇒ Object (private)



47
48
49
50
51
52
53
# File 'lib/vets/attributes.rb', line 47

def define_setter(name, klass, array)
  define_method("#{name}=") do |value|
    casted_value = Vets::Attributes::Value.cast(name, klass, value, array:)
    instance_variable_set("@#{name}", casted_value)
    casted_value
  end
end