From df4d08c44ac3e96336d29a360aafdc4b2a3e96fc Mon Sep 17 00:00:00 2001 From: Marc-Andre Lafortune Date: Fri, 25 Sep 2020 20:55:38 -0400 Subject: [PATCH] [ruby/ostruct] Avoid calling initialize --- lib/ostruct.rb | 16 +++++++++++----- test/ostruct/test_ostruct.rb | 9 +++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/lib/ostruct.rb b/lib/ostruct.rb index 6f8f255511..31f46bba4d 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -121,11 +121,10 @@ class OpenStruct # data # => # # def initialize(hash=nil) - @table = {} if hash - hash.each_pair do |k, v| - set_ostruct_member_value!(k, v) - end + update_to_values!(hash) + else + @table = {} end end @@ -137,7 +136,14 @@ class OpenStruct private def initialize_dup(orig) # :nodoc: 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 # diff --git a/test/ostruct/test_ostruct.rb b/test/ostruct/test_ostruct.rb index 0628094306..8e1aedd896 100644 --- a/test/ostruct/test_ostruct.rb +++ b/test/ostruct/test_ostruct.rb @@ -204,6 +204,15 @@ class TC_OpenStruct < Test::Unit::TestCase assert_instance_of(c, os) 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 os = OpenStruct.new class << os