Module: ActiveModelAttributes::ClassMethods

Defined in:
lib/active_model_attributes.rb

Constant Summary collapse

SERVICE_ATTRIBUTES =
%i(default user_provided_default).freeze

Instance Method Summary collapse

Instance Method Details

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



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

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



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

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



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

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