3

How do I use OpenStruct's marshal_load utility? It doesn't appear to work as intended.

The docs give this example, but it doesn't appear to work.

require 'ostruct'

event = OpenStruct.new
hash = { 'time' => Time.now, 'title' => 'Birthday Party' }
event.marshal_load(hash)
event.title # => nil

If not this way, how do I load a hash into an OpenStruct (without using the constructor)?

For context: I'm loading a hash in from a YAML file and loading it into an existing instance of an OpenStruct subclass.

Cody A. Ray
  • 5,869
  • 1
  • 37
  • 31

2 Answers2

5

Try with a symbol based hash. That worked for me.

#works.rb

hash = { :time => Time.now, :title => 'Birthday Party' }
event.marshal_load(hash)
Kashyap
  • 4,696
  • 24
  • 26
  • Interesting! Its not what's documented, but I confirmed it works. YAML.load_file returns string keys, but they can be converted to symbols before loading, I reckon. – Cody A. Ray Jan 18 '13 at 22:31
4

The marshal_load method exists to provide support for Marshal.load.

event = OpenStruct.new({ 'time' => Time.now, 'title' => 'Birthday Party' })
binary = Marshal.dump(event)
loaded = Marshal.load(binary) # the OpenStruct

The easiest way to programmatically load a hash into a struct is using send:

event = OpenStruct.new
hash.each do |key, value|
  event.send("#{key}=", value)
end
Yehuda Katz
  • 28,535
  • 12
  • 89
  • 91
  • I understand the original intent of providing this method, but its still not working as expected. The posted example is directly from the docs. That being said, I ended up overriding the marshal_laod method in my OpenStruct subclass and using `send` to load the hash. – Cody A. Ray Jan 18 '13 at 22:30