[ruby/ostruct] Avoid calling initialize

This commit is contained in:
Marc-Andre Lafortune 2020-09-25 20:55:38 -04:00 committed by Marc-André Lafortune
parent fb16c3dce2
commit df4d08c44a
Notes: git 2020-10-01 07:11:52 +09:00
2 changed files with 20 additions and 5 deletions

View File

@ -121,11 +121,10 @@ class OpenStruct
# data # => #<OpenStruct country="Australia", capital="Canberra"> # data # => #<OpenStruct country="Australia", capital="Canberra">
# #
def initialize(hash=nil) def initialize(hash=nil)
@table = {}
if hash if hash
hash.each_pair do |k, v| update_to_values!(hash)
set_ostruct_member_value!(k, v) else
end @table = {}
end end
end end
@ -137,7 +136,14 @@ class OpenStruct
private def initialize_dup(orig) # :nodoc: private def initialize_dup(orig) # :nodoc:
super super
initialize(@table) update_to_values!(@table)
end
private def update_to_values!(hash) # :nodoc:
@table = {}
hash.each_pair do |k, v|
set_ostruct_member_value!(k, v)
end
end end
# #

View File

@ -204,6 +204,15 @@ class TC_OpenStruct < Test::Unit::TestCase
assert_instance_of(c, os) assert_instance_of(c, os)
end end
def test_initialize_subclass
c = Class.new(OpenStruct) {
def initialize(x,y={})super(y);end
}
o = c.new(1, {a: 42})
assert_equal(42, o.dup.a)
assert_equal(42, o.clone.a)
end
def test_private_method def test_private_method
os = OpenStruct.new os = OpenStruct.new
class << os class << os