Class: Anchormodel::ActiveModelTypeValueSingle

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

Overview

Direct Known Subclasses

ActiveModelTypeValueMulti

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attribute) ⇒ ActiveModelTypeValueSingle

Returns a new instance of ActiveModelTypeValueSingle.



5
6
7
8
# File 'lib/anchormodel/active_model_type_value_single.rb', line 5

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

Instance Attribute Details

#attributeObject (readonly)



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

def attribute
  @attribute
end

Instance Method Details

#cast(value) ⇒ Object

This converts DB or input to an Anchormodel instance



15
16
17
18
19
# File 'lib/anchormodel/active_model_type_value_single.rb', line 15

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

#changed_in_place?(raw_old_value, value) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
53
# File 'lib/anchormodel/active_model_type_value_single.rb', line 50

def changed_in_place?(raw_old_value, value)
  old_value = deserialize(raw_old_value)
  old_value != value
end

#serializable?(value) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
43
44
45
46
47
48
# File 'lib/anchormodel/active_model_type_value_single.rb', line 39

def serializable?(value)
  return case value
         when Symbol, String
           @attribute.anchormodel_class.valid_keys.exclude?(value.to_sym)
         when nil, @attribute.anchormodel_class
           true
         else
           false
         end
end

#serialize(value) ⇒ Object

This converts an Anchormodel instance to string for DB



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/anchormodel/active_model_type_value_single.rb', line 22

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

#typeObject



10
11
12
# File 'lib/anchormodel/active_model_type_value_single.rb', line 10

def type
  :anchormodel
end