Project

General

Profile

Feature #8382 ยป ostruct_yaml.patch

pietro (Pietro Monteiro), 05/08/2013 01:07 PM

View differences:

ChangeLog
1
Wed May  8 10:54:09 2013  Pietro Monteiro  <pietro@riseup.net>
2

  
3
	* lib/ostruct.rb (encode_with, init_with): Format YAML dump and
4
	  create getters and setters after load.
5

  
1 6
Wed May  8 06:42:56 2013  NARUSE, Yui  <naruse@ruby-lang.org>
2 7

  
3 8
	* ext/socket/socket.c (socket_s_ip_address_list): fix wrongly filled
lib/ostruct.rb
145 145
  end
146 146

  
147 147
  #
148
  # Provides marshalling support for use by the YAML library.
149
  #
150
  def encode_with(coder)
151
    @table.each_pair do |key, value|
152
      coder[key.to_s] = value
153
    end
154
  end
155

  
156
  #
157
  # Provides marshalling support for use by the YAML library.
158
  #
159
  def init_with(coder)
160
    @table = {}
161
    coder.map.each_pair do |key, value|
162
      key = key.to_sym
163
      @table[key] = value
164
      new_ostruct_member(key)
165
    end
166
  end
167

  
168
  #
148 169
  # Used internally to check if the OpenStruct is able to be
149 170
  # modified before granting access to the internal Hash table to be modified.
150 171
  #
test/ostruct/test_ostruct.rb
1 1
require 'test/unit'
2 2
require 'ostruct'
3
require 'yaml'
3 4

  
4 5
class TC_OpenStruct < Test::Unit::TestCase
5 6
  def test_initialize
......
114 115
    assert_equal true, os1.eql?(os1.dup)
115 116
    assert_equal os1.hash, os1.dup.hash
116 117
  end
118

  
119
  def test_yaml
120
    h = {name: "John Smith", age: 70, pension: 300.0}
121
    yaml = "--- !ruby/object:OpenStruct\nname: John Smith\nage: 70\npension: 300.0\n"
122
    os1 = OpenStruct.new(h)
123
    os2 = YAML.load(os1.to_yaml)
124
    assert_equal yaml, os1.to_yaml
125
    assert_equal os1, os2
126
    assert_equal true, os1.eql?(os2)
127
    assert_equal os1.methods, os2.methods
128
  end
117 129
end