Simple hash serlializable object

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.


class Foo
  attr_accessor :bar, :none

foo = do |f| = true
  f.none = false

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?


Maybe something like the following using OpenStruct?

require "ostruct"

class HashableStruct < OpenStruct
   def self.from_hash(hash)

   def to_hash

f = HashableStruct.from_hash(:bar => true, :none => false)
p f # => #<HashableStruct bar=true, none=false>
p f.to_hash # => {:bar=>true, :none=>false}

I don't see the benefit of using a block though, it only adds another


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.

Well, ok, except it doesn't catch invalid attributes since you can't
restrict them. Kind of icky but it works.

I think that Struct might be your best bet:

It’ll disallow invalid keys, plus, is way faster than OpenStruct.


Pat, thanks for that great example!