I frequently find the need to have an object with specific attributes,
preferably initializable with a code block and/or a hash, that I also
want serializable/deserializable to a hash.
Example:
class Foo
attr_accessor :bar, :none
end
foo = Foo.new do |f|
f.bar = true
f.none = false
end
puts s = foo.to_hash
{ :bar => true, :none => false}
foo = Foo.from_hash(s)
Of course I could write a library to do this, but it seems obvious
enough that it would exist. Am I missing it?
Thanks for the suggestion. That looks like what I need.
The benefits of the block are that you are writing to the object
instead of a hashtable, so incorrect attributes are caught sooner. It
also allows more flexibility in the code, i.e. everything doesn't have
to be one statement so you can do loops, conditionals, etc.