Skip to content

Instantly share code, notes, and snippets.

@doughsay
Last active August 29, 2015 14:22
Show Gist options
  • Save doughsay/5cea9c32946f6a1f19ec to your computer and use it in GitHub Desktop.
Save doughsay/5cea9c32946f6a1f19ec to your computer and use it in GitHub Desktop.
Mongoid serialization and deserialization of Virtus value objects
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
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