Created
March 5, 2013 23:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# 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