Search code examples
rubyopenstruct

Using marshal_load with OpenStruct


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.


Solution

  • 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