Module: MotionRecord::Serialization::ClassMethods

Defined in:
lib/motion_record/serialization.rb

Instance Method Summary collapse

Instance Method Details

#deserialize_table_params(params) ⇒ Object

Deserialize a Hash of attributes from their database representation

params - a Hash of Symbol column names to SQLite values

Returns a Hash with all values replaced by their deserialized versions



33
34
35
36
37
38
# File 'lib/motion_record/serialization.rb', line 33

def deserialize_table_params(params)
  params.each_with_object({}) do |name_and_value, attributes|
    name, value = name_and_value
    attributes[name.to_sym] = serializer(name.to_sym).deserialize(value)
  end
end

#serialize(attribute, serializer_class_or_sym) ⇒ Object

Register a new attribute serializer

attribute - Symbol name of the attribute serializer_class_or_sym - One of :time, :boolean, :json, :date or a custom

subclass of Serialization::BaseSerializer


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/motion_record/serialization.rb', line 9

def serialize(attribute, serializer_class_or_sym)
  if serializer_class_or_sym.is_a?(Symbol)
    self.serializer_classes[attribute] = case serializer_class_or_sym
    when :time
      Serialization::TimeSerializer
    when :date
      Serialization::DateSerializer
    when :boolean
      Serialization::BooleanSerializer
    when :json
      Serialization::JSONSerializer
    else
      raise "Unknown serializer #{serializer_class_or_sym.inspect}"
    end
  else
    self.serializer_classes[attribute] = serializer_class_or_sym
  end
end

#serialize_table_params(hash) ⇒ Object

Serialize a Hash of attributes to their database representation

params - a Hash of Symbol column names to their attribute values

Returns a Hash with all values replaced by their serialized versions



45
46
47
48
49
50
# File 'lib/motion_record/serialization.rb', line 45

def serialize_table_params(hash)
  hash.each_with_object({}) do |attribute_and_value, params|
    attribute, value = attribute_and_value
    params[attribute] = serializer(attribute).serialize(value)
  end
end