Writing records in YAML using deserialization

177 views
Skip to first unread message

Turadg

unread,
Jan 21, 2011, 12:58:45 PM1/21/11
to Mongoid
My goal is to have a syntax for writing and revising models so that a
whole object graph can be expressed in one text document. I've been
using YAML because it's human-readable and does serialization/
deserialization from Ruby objects.

I've been running into trouble deserializing objects that include
Mongoid:Document. Say I have a class SomeModel:

class SomeModel
include Mongoid::Document

field :foo
end

I can construct it, serialize it to YAML, and deserialize it fine:

sm = SomeModel.new
sm.foo = 'bar'
YAML::load(sm.to_yaml)
=> #<SomeModel _id: 4d39c450b6eee66fa2000006, foo: "bar">

But if I try to start with a simple YAML, it fails:

sm2 = YAML::load(<<EOF
--- !ruby/object:SomeModel
foo: baz
EOF
)
(Object doesn't support #inspect)
=>

Through some trial and error, the minimal case is:

sm3 = YAML::load(<<EOF
--- !ruby/object:SomeModel
attributes:
_type: SomeModel
foo: bar
new_record: true
EOF
)
=> #<SomeModel _id: , foo: "bar">
sm3.save
=> true

So that works but it's unnecessarily verbose. Is there any way I can
make a working Mongoid model instance from the syntax above in m2?

Thanks for any pointers! I started with Ruby a couple weeks ago so
feel free to correct any misguided thinking.

Turadg

Durran Jordan

unread,
Jan 21, 2011, 1:07:38 PM1/21/11
to mon...@googlegroups.com
Why are you using YAML and not JSON? Mongoid already supports that serialization out of the box. However that being said - what about trying this (not sure if it will work, but maybe, just maybe...)

Try serializing not the Mongoid::Document, but the Hash representation of it :

some_model.serializable_hash

You can include associations as well:

some_model.serializable_hash(:include => [ :name, :addresses ])

YAML should handle that fine, then when loading take the hash you get back from the YAML and use:

Mongoid::Factory.build(SomeModel, the_hash)

2011/1/21 Turadg <tur...@gmail.com>

Turadg

unread,
Feb 8, 2011, 8:40:45 PM2/8/11
to Mongoid
Thanks for your reply, btw. I gradually realized I was too new to Ruby
and Rails to be venturing off the golden path. I'll be back on Mongo
when I've got better shoes.

FWIW, I was using YAML to handle cross-object references and for an
easier to type syntax. I went ahead and set up forms-based editing
instead.
Reply all
Reply to author
Forward
0 new messages