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)


34
35
36
# File 'lib/anchormodel/active_model_type_value.rb', line 34

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

#deserialize(value) ⇒ Object



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

def deserialize(value)
  return value if value.is_a?(@attribute.anchor_class)
  return @attribute.anchor_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
# File 'lib/anchormodel/active_model_type_value.rb', line 13

def serialize(value)
  return case value
         when Symbol, String
           unless @attribute.anchor_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.anchor_class
           value.key.to_s
         when nil
           nil
         else
           fail "Attempt to set #{@attribute.attribute_name} to unsupported type #{value.class}"
         end
end