Class: Undo::Serializer::ActiveModel

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

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ ActiveModel

Returns a new instance of ActiveModel.



6
7
8
9
10
11
# File 'lib/undo/serializer/active_model.rb', line 6

def initialize(*args)
  options = args.extract_options!
  @serializer = args.first
  @serializer_source = options.fetch :serializer,
    ->(object) { object.active_model_serializer.new object }
end

Instance Method Details

#deserialize(hash) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/undo/serializer/active_model.rb', line 17

def deserialize(hash)
  hash.each do |object_class, data|
    next unless data.is_a? Hash
    data.stringify_keys!

    object_class = object_class.to_s.camelize.constantize
    object = object_class.where(id: data.fetch("id")).first_or_initialize

    data.each do |field, value|
      next if "id" == field && object.persisted?
      _, association = field.to_s.split("___")
      if association
        deserialize_association(association, value)
      else
        object.send "#{field}=", value # not public_send!
      end
    end

    object.save!
    return object
  end
end

#serialize(object) ⇒ Object



13
14
15
# File 'lib/undo/serializer/active_model.rb', line 13

def serialize(object)
  serializer(object).as_json
end