Module: ActiveModelAttributes::ClassMethods

Defined in:
lib/active_model_attributes.rb

Instance Method Summary collapse

Instance Method Details

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



17
18
19
20
21
22
# File 'lib/active_model_attributes.rb', line 17

def attribute(name, cast_type, **options)
  self.attributes_registry = attributes_registry.merge(name => [cast_type, options])

  define_attribute_reader(name, options)
  define_attribute_writer(name, cast_type, options)
end

#define_attribute_reader(name, options) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/active_model_attributes.rb', line 24

def define_attribute_reader(name, options)
  provided_default = options.fetch(:default) { NO_DEFAULT_PROVIDED }
  define_method name do
    return instance_variable_get("@#{name}") if instance_variable_defined?("@#{name}")
    return if provided_default == NO_DEFAULT_PROVIDED
    provided_default.respond_to?(:call) && provided_default.call || provided_default
  end
end

#define_attribute_writer(name, cast_type, options) ⇒ Object



33
34
35
36
37
38
# File 'lib/active_model_attributes.rb', line 33

def define_attribute_writer(name, cast_type, options)
  define_method "#{name}=" do |val|
    deserialized_value = ActiveModel::Type.lookup(cast_type).deserialize(val)
    instance_variable_set("@#{name}", deserialized_value)
  end
end