Skip to content

Commit

Permalink
[ruby/ostruct] Avoid calling initialize
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Sep 30, 2020
1 parent fb16c3d commit df4d08c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/ostruct.rb
Expand Up @@ -121,11 +121,10 @@ class OpenStruct
# 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

Expand All @@ -137,7 +136,14 @@ def initialize(hash=nil)

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

#
Expand Down
9 changes: 9 additions & 0 deletions test/ostruct/test_ostruct.rb
Expand Up @@ -204,6 +204,15 @@ def initialize(x,y={})super(y);end
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
Expand Down

0 comments on commit df4d08c

Please sign in to comment.