marshal_load(x) public

Provides marshalling support for use by the Marshal library. Accepting a Hash of keys and values which will be used to populate the internal table

require 'ostruct'

event = OpenStruct.new
hash = { 'time' => Time.now, 'title' => 'Birthday Party' }
event.title # => 'Birthday Party'
Show source
Register or log in to add new notes.
May 19, 2009
0 thanks

Method functions like Hash#merge!

This method functions a lot like Hash#merge! only with a different name.

f = OpenStruct.new
# => #<OpenStruct>
f.marshal_load({:foo => 'bar'})
# => #<OpenStruct foo="bar">
# => "bar"
May 20, 2009
0 thanks

Symbol Keys Only

While OpenStruct#new is rather indifferent to the kind of keys submitted, marshal_load requires Symbol keys only. Use of a string can cause difficulty.

To fix:

marshal_load(hash.inject({ }) { |h, (k,v)| h[k.to_sym] = v; h })

As a note, Rails has the Hash#symbolize_keys method that can be used in place.