Skip to content

Instantly share code, notes, and snippets.

@rubish
Created March 5, 2013 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubish/5095346 to your computer and use it in GitHub Desktop.
Save rubish/5095346 to your computer and use it in GitHub Desktop.
custom serializer to handle root and embedded documents alike in the association. WARNING: behaves like a field rather than an association
##
# class Activity
# include Mongoid::Document
#
# field :trackable, type: ShallowDocument
# end
##
class ShallowDocument
include Mongoid::Fields::Serializable
def deserialize(object={})
return nil if object.blank?
result = (object['klass'].constantize).where(_id: object['_id']).first
(object['selector'] || []).each do |message|
result = result.send(*message)
end if result
result
end
def serialize(object)
return object unless object.is_a?(::Mongoid::Document)
attr = {}
root = object._root
attr.store('klass', root.class.to_s)
attr.store('_id', root._id.to_s)
attr.store('selector', object.selector_from(root)) if object.embedded?
attr
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment