to_h?

12 views
Skip to first unread message

Avdi Grimm

unread,
Oct 17, 2008, 9:26:09 AM10/17/08
to ruby-doodle
Hello,

What is the best way to convert an object's doodly attributes to a
hash of names-to-values?

Thanks,

--
Avdi

Sean O'Halpin

unread,
Oct 17, 2008, 11:35:01 AM10/17/08
to ruby-...@googlegroups.com

Hi Avdi,

Here's a hacky way that I'm using currently:

class Doodle
module BaseMethods
# create 'pure' hash of scalars only from attributes - hacky but works :)
require 'yaml'
def to_hash
Doodle::Utils.symbolize_keys!(YAML::load(to_yaml.gsub(/!ruby\/object:.*$/,
'')) || { })
end
end
end

This converts the doodle and all nested contained objects into a hash
of :symbol => value pairs. If all the contained objects are themselves
doodles or native Ruby values (scalars, hashes, arrays), then you
should be able to initialize a new doodle from the hash. In other
words, I'm aiming for this to always work:

doodle2 = DoodledClass(doodle1.to_hash)
doodle2 == doodle1

where the contained objects are instances of subclasses of Doodle.
However, I haven't quite worked out what I want to do about non-Doodle
classes - I guess I should preserve them as is. Any ideas?

I'm putting together a new release (0.1.9) that includes this hack
(and some nice non-hacky new features). I'll be releasing this
weekend.

Regards,
Sean

Reply all
Reply to author
Forward
0 new messages