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.

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?

Hi,

Maybe something like the following using OpenStruct?

require "ostruct"

class HashableStruct < OpenStruct
   def self.from_hash(hash)
     new(hash)
   end

   def to_hash
     @table
   end
end

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
line.

HTH,
Eloy

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: https://gist.github.com/afe18b5713b036e2324f

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

Pat

Pat, thanks for that great example!