Class: Anchormodel::ActiveModelTypeValue

Inherits:
ActiveModel::Type::Value
  • Object
show all
Defined in:
lib/anchormodel/active_model_type_value.rb

Overview

Instance Method Summary collapse

Constructor Details

#initialize(attribute) ⇒ ActiveModelTypeValue

Returns a new instance of ActiveModelTypeValue.



3
4
5
6
# File 'lib/anchormodel/active_model_type_value.rb', line 3

def initialize(attribute)
  super()
  @attribute = attribute
end

Instance Method Details

#cast(value) ⇒ Object



8
9
10
# File 'lib/anchormodel/active_model_type_value.rb', line 8

def cast(value)
  serialize value
end

#changed?(old_value, new_value, _new_value_before_type_cast) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/anchormodel/active_model_type_value.rb', line 36

def changed?(old_value, new_value, _new_value_before_type_cast)
  return deserialize(old_value) != deserialize(new_value)
end

#deserialize(value) ⇒ Object



30
31
32
33
34
# File 'lib/anchormodel/active_model_type_value.rb', line 30

def deserialize(value)
  value = value.presence
  return value if value.is_a?(@attribute.anchormodel_class)
  return @attribute.anchormodel_class.find(value)
end

#serialize(value) ⇒ Object

Implementing this instead of cast to force key validation in any case



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/anchormodel/active_model_type_value.rb', line 13

def serialize(value)
  value = value.presence
  return case value
         when Symbol, String
           unless @attribute.anchormodel_class.valid_keys.include?(value.to_sym)
             fail("Attempt to set #{@attribute.attribute_name} to unsupported key #{value.inspect}.")
           end
           value.to_s
         when @attribute.anchormodel_class
           value.key.to_s
         when nil
           nil
         else
           fail "Attempt to set #{@attribute.attribute_name} to unsupported type #{value.class}"
         end
end