[前][次][番号順一覧][スレッド一覧]

ruby-changes:63222

From: Marc-Andre <ko1@a...>
Date: Thu, 1 Oct 2020 07:11:42 +0900 (JST)
Subject: [ruby-changes:63222] df4d08c44a (master): [ruby/ostruct] Avoid calling initialize

https://git.ruby-lang.org/ruby.git/commit/?id=df4d08c44a

From df4d08c44ac3e96336d29a360aafdc4b2a3e96fc Mon Sep 17 00:00:00 2001
From: Marc-Andre Lafortune <github@m...>
Date: Fri, 25 Sep 2020 20:55:38 -0400
Subject: [ruby/ostruct] Avoid calling initialize


diff --git a/lib/ostruct.rb b/lib/ostruct.rb
index 6f8f255..31f46bb 100644
--- a/lib/ostruct.rb
+++ b/lib/ostruct.rb
@@ -121,11 +121,10 @@ class OpenStruct https://github.com/ruby/ruby/blob/trunk/lib/ostruct.rb#L121
   #   data   # => #<OpenStruct country="Australia", capital="Canberra">
   #
   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 https://github.com/ruby/ruby/blob/trunk/lib/ostruct.rb#L136
 
   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 0628094..8e1aedd 100644
--- a/test/ostruct/test_ostruct.rb
+++ b/test/ostruct/test_ostruct.rb
@@ -204,6 +204,15 @@ class TC_OpenStruct < Test::Unit::TestCase https://github.com/ruby/ruby/blob/trunk/test/ostruct/test_ostruct.rb#L204
     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
-- 
cgit v0.10.2


--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]