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

ruby-changes:62950

From: Marc-Andre <ko1@a...>
Date: Tue, 15 Sep 2020 01:47:32 +0900 (JST)
Subject: [ruby-changes:62950] ebb8de7302 (master): [ruby/ostruct] Refactor handling of frozen OpenStruct. Simplify `new_ostruct_member!`

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

From ebb8de730269a8c18a553e3dea7a7603b13d2328 Mon Sep 17 00:00:00 2001
From: Marc-Andre Lafortune <github@m...>
Date: Tue, 8 Sep 2020 16:13:15 -0400
Subject: [ruby/ostruct] Refactor handling of frozen OpenStruct. Simplify
 `new_ostruct_member!`


diff --git a/lib/ostruct.rb b/lib/ostruct.rb
index 477b67c..18850bf 100644
--- a/lib/ostruct.rb
+++ b/lib/ostruct.rb
@@ -93,9 +93,7 @@ class OpenStruct https://github.com/ruby/ruby/blob/trunk/lib/ostruct.rb#L93
     @table = {}
     if hash
       hash.each_pair do |k, v|
-        k = k.to_sym
-        @table[k] = v
-        new_ostruct_member!(k)
+        self[k] = v
       end
     end
   end
@@ -166,41 +164,30 @@ class OpenStruct https://github.com/ruby/ruby/blob/trunk/lib/ostruct.rb#L164
   end
 
   #
-  # Used internally to check if the OpenStruct is able to be
-  # modified before granting access to the internal Hash table to be modified.
-  #
-  def modifiable? # :nodoc:
-    begin
-      @modifiable = true
-    rescue
-      raise FrozenError, "can't modify frozen #{self.class}", caller(3)
-    end
-    @table
-  end
-  private :modifiable?
-
-  #
   # Used internally to defined properties on the
   # OpenStruct. It does this by using the metaprogramming function
   # define_singleton_method for both the getter method and the setter method.
   #
   def new_ostruct_member!(name) # :nodoc:
-    name = name.to_sym
     unless respond_to?(name)
       define_singleton_method(name) { @table[name] }
-      define_singleton_method("#{name}=") {|x| modifiable?[name] = x}
+      define_singleton_method("#{name}=") {|x| @table[name] = x}
     end
-    name
   end
   private :new_ostruct_member!
 
+  def freeze
+    @table.freeze
+    super
+  end
+
   def method_missing(mid, *args) # :nodoc:
     len = args.length
     if mname = mid[/.*(?==\z)/m]
       if len != 1
         raise ArgumentError, "wrong number of arguments (given #{len}, expected 1)", caller(1)
       end
-      modifiable?[new_ostruct_member!(mname)] = args[0]
+      self[mname]= args[0]
     elsif len == 0
     elsif @table.key?(mid)
       raise ArgumentError, "wrong number of arguments (given #{len}, expected 0)"
@@ -240,7 +227,9 @@ class OpenStruct https://github.com/ruby/ruby/blob/trunk/lib/ostruct.rb#L227
   #   person.age          # => 42
   #
   def []=(name, value)
-    modifiable?[new_ostruct_member!(name)] = value
+    name = name.to_sym
+    new_ostruct_member!(name)
+    @table[name] = value
   end
 
   # :call-seq:
-- 
cgit v0.10.2


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

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