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



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

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)

  if cast_type.is_a?(Symbol)
    cast_type = ActiveModel::Type.lookup(cast_type, **options.except(:default))
  end
  self.attribute_types = attribute_types.merge(name.to_s => cast_type)
end

#define_attribute_reader(name, options) ⇒ Object



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

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
      instance_variable_set("@#{name}", provided_default.respond_to?(:call) && provided_default.call || provided_default)
    end
  end
  include wrapper
end

#define_attribute_writer(name, cast_type, options) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/active_model_attributes.rb', line 45

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:

  • (Boolean)


70
71
72
# File 'lib/active_model_attributes.rb', line 70

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

#type_for_attribute(attr) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/active_model_attributes.rb', line 58

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