Last active
August 29, 2015 14:22
-
-
Save doughsay/5cea9c32946f6a1f19ec to your computer and use it in GitHub Desktop.
Mongoid serialization and deserialization of Virtus value objects
This file contains 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 Bar | |
include Virtus::ValueObject | |
include Virtus::ValueObject::Mongoize | |
values do | |
attribute :bar, String | |
end | |
end | |
class Foo | |
include Mongoid::Document | |
field :bar, :type => Bar | |
end | |
x = Foo.new(:bar => Bar.new(:bar => 'lol')) | |
x.save! | |
y = Foo.where(:bar => x.bar).first | |
y == x | |
y.bar == x.bar |
This file contains 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
module Virtus | |
module ValueObject | |
module Mongoize | |
def self.included(base) | |
base.extend ClassMethods | |
base.class_eval do | |
def mongoize | |
as_json | |
end | |
end | |
end | |
module ClassMethods | |
def demongoize(object) | |
new(object) | |
end | |
def mongoize(object) | |
case object | |
when self then object.mongoize | |
when Hash then new(object).mongoize | |
else object | |
end | |
end | |
def evolve(object) | |
case object | |
when self then object.mongoize | |
else object | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment