Class: Quebert::Serializer::ActiveRecord

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

Overview

Deal with converting an AR to/from a hash that we can send over the wire.

Class Method Summary collapse

Class Method Details

.deserialize(hash) ⇒ Object


66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/quebert/serializer.rb', line 66

def self.deserialize(hash)
  hash = Support.stringify_keys(hash)
  model = Support.constantize(hash.delete('model'))
  if attrs = Support.stringify_keys(hash.delete('attributes'))
    if id = attrs.delete('id')
      # This has been persisited, so just find it from the db
      model.find(id)
    else
      # Looks like its not around! Better generate it from attributes
      record = model.new
      record.attributes.each do |attr, val|
        record.send("#{attr}=", attrs[attr])
      end
      record
    end
  else
    model.new
  end
end

.serialize(record) ⇒ Object


58
59
60
61
62
63
64
# File 'lib/quebert/serializer.rb', line 58

def self.serialize(record)
  attrs = record.attributes.inject({}) do |hash, (attr, val)|
    hash[attr] = val
    hash
  end
  { 'model' => record.class.model_name.to_s, 'attributes' => attrs }
end