Class: Undo::Serializer::ActiveModel

Inherits:
Object
  • Object
show all
Defined in:
lib/undo/serializer/active_model.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ ActiveModel

Returns a new instance of ActiveModel.



4
5
6
# File 'lib/undo/serializer/active_model.rb', line 4

def initialize(options = {})
  load_options options
end

Instance Method Details

#deserialize(object, options = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/undo/serializer/active_model.rb', line 34

def deserialize(object, options = {})
  return object.map do |record|
    deserialize record
  end if array? object

  load_options options

  hash = symbolize_keys object
  object_meta = hash.fetch :meta
  associations = hash.fetch :associations
  attributes = hash.fetch :attributes

  with_transaction do
    initialize_object(object_meta).tap do |object|
      attributes.each do |field, value|
        deserialize_field object, field, value
      end

      # QUESTION: Set associations? object.association_name = deserialize association ?
      associations.each do |(association_name, association)|
        deserialize association
      end

      persist object
    end
  end
end

#serialize(object, options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/undo/serializer/active_model.rb', line 8

def serialize(object, options = {})
  return object.map do |record|
    serialize record, options
  end if array? object

  load_options options

  attributes = serialize_attributes(object) || {}
  associations = {}
  Array(options[:include]).map do |association|
    associations[association] = serialize(object.public_send association)
  end
  pk_attributes = symbolize_keys(attributes).select do |attribute|
    primary_key_fields.include? attribute
  end

  {
    attributes: attributes,
    associations: associations,
    meta: {
      pk_attributes: pk_attributes,
      class_name: object.class.name,
    }
  }
end