diff --git a/ChangeLog b/ChangeLog index 8aabf6d..f89c7c1 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Wed May 8 10:54:09 2013 Pietro Monteiro + + * lib/ostruct.rb (encode_with, init_with): Format YAML dump and + create getters and setters after load. + Wed May 8 06:42:56 2013 NARUSE, Yui * ext/socket/socket.c (socket_s_ip_address_list): fix wrongly filled diff --git a/lib/ostruct.rb b/lib/ostruct.rb index df09cc9..b9d8189 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -145,6 +145,27 @@ class OpenStruct end # + # Provides marshalling support for use by the YAML library. + # + def encode_with(coder) + @table.each_pair do |key, value| + coder[key.to_s] = value + end + end + + # + # Provides marshalling support for use by the YAML library. + # + def init_with(coder) + @table = {} + coder.map.each_pair do |key, value| + key = key.to_sym + @table[key] = value + new_ostruct_member(key) + end + end + + # # Used internally to check if the OpenStruct is able to be # modified before granting access to the internal Hash table to be modified. # diff --git a/test/ostruct/test_ostruct.rb b/test/ostruct/test_ostruct.rb index d82bab9..b15a802 100644 --- a/test/ostruct/test_ostruct.rb +++ b/test/ostruct/test_ostruct.rb @@ -1,5 +1,6 @@ require 'test/unit' require 'ostruct' +require 'yaml' class TC_OpenStruct < Test::Unit::TestCase def test_initialize @@ -114,4 +115,15 @@ class TC_OpenStruct < Test::Unit::TestCase assert_equal true, os1.eql?(os1.dup) assert_equal os1.hash, os1.dup.hash end + + def test_yaml + h = {name: "John Smith", age: 70, pension: 300.0} + yaml = "--- !ruby/object:OpenStruct\nname: John Smith\nage: 70\npension: 300.0\n" + os1 = OpenStruct.new(h) + os2 = YAML.load(os1.to_yaml) + assert_equal yaml, os1.to_yaml + assert_equal os1, os2 + assert_equal true, os1.eql?(os2) + assert_equal os1.methods, os2.methods + end end