Class: Anchormodel::ActiveModelTypeValueSingle

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

Overview

Instance Method Summary collapse

Constructor Details

#initialize(attribute) ⇒ ActiveModelTypeValueSingle

Returns a new instance of ActiveModelTypeValueSingle.



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

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

Instance Method Details

#cast(value) ⇒ Object

This converts an Anchormodel instance to string for DB



13
14
15
16
17
# File 'lib/anchormodel/active_model_type_value_single.rb', line 13

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)


48
49
50
51
# File 'lib/anchormodel/active_model_type_value_single.rb', line 48

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

#serializable?(value) ⇒ Boolean

Returns:

  • (Boolean)


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

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 DB or input to an Anchormodel instance



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

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



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

def type
  :anchormodel
end