[ruby/ostruct] Allow overriding public methods

[Fixes https://bugs.ruby-lang.org/issues/15409]
This commit is contained in:
Marc-Andre Lafortune 2020-09-08 16:30:02 -04:00
parent ebb8de7302
commit 8eefa8f373
2 changed files with 9 additions and 3 deletions

View File

@ -100,9 +100,9 @@ class OpenStruct
# Duplicates an OpenStruct object's Hash table.
def initialize_copy(orig) # :nodoc:
orig.table.each_key{|key| new_ostruct_member!(key)}
super
@table = @table.dup
@table.each_key{|key| new_ostruct_member!(key)}
end
#
@ -159,8 +159,8 @@ class OpenStruct
# Provides marshalling support for use by the Marshal library.
#
def marshal_load(x)
x.each_key{|key| new_ostruct_member!(key)}
@table = x
@table.each_key{|key| new_ostruct_member!(key)}
end
#
@ -169,7 +169,7 @@ class OpenStruct
# define_singleton_method for both the getter method and the setter method.
#
def new_ostruct_member!(name) # :nodoc:
unless respond_to?(name)
unless @table.key?(name)
define_singleton_method(name) { @table[name] }
define_singleton_method("#{name}=") {|x| @table[name] = x}
end

View File

@ -235,4 +235,10 @@ class TC_OpenStruct < Test::Unit::TestCase
assert_equal(:foo, os.puts)
assert_equal(:bar, os.format)
end
def test_overriden_public_methods
os = OpenStruct.new(method: :foo, class: :bar)
assert_equal(:foo, os.method)
assert_equal(:bar, os.class)
end
end