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 = ActiveModel::Type::Value.new, **options) ⇒ Object



20
21
22
23
24
25
# File 'lib/active_model_attributes.rb', line 20

def attribute(name, cast_type = ActiveModel::Type::Value.new, **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



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/active_model_attributes.rb', line 27

def define_attribute_reader(name, options)
  wrapper = Module.new do
    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
  include wrapper
end

#define_attribute_writer(name, cast_type, options) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/active_model_attributes.rb', line 39

def define_attribute_writer(name, cast_type, options)
  wrapper = Module.new do
    define_method "#{name}=" do |val|
      if cast_type.is_a?(Symbol)
        cast_type = ActiveModel::Type.lookup(cast_type, **options.except(*SERVICE_ATTRIBUTES))
      end
      deserialized_value = cast_type.cast(val)
      instance_variable_set("@#{name}", deserialized_value)
    end
  end
  include wrapper
end

#has_attribute?(attr) ⇒ Boolean

Returns:



64
65
66
# File 'lib/active_model_attributes.rb', line 64

def has_attribute?(attr)
  attributes_registry.key?(attr.to_sym)
end

#type_for_attribute(attr) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/active_model_attributes.rb', line 52

def type_for_attribute(attr)
  type_desc = attributes_registry[attr.to_sym]
  return ActiveModel::Type::Value.new if type_desc.nil?

  if type_desc[0].is_a?(Symbol)
    type, options = type_desc
    ActiveModel::Type.lookup(type, **options.except(*SERVICE_ATTRIBUTES))
  else
    type_desc[0]
  end
end