[lib/ostruct] Allow overriding of block_given?

This commit is contained in:
Marc-Andre Lafortune 2021-06-14 10:07:51 -04:00 committed by Marc-André Lafortune
parent fc98602ecc
commit 52369fc545
Notes: git 2021-06-15 01:29:15 +09:00
2 changed files with 7 additions and 3 deletions

View File

@ -197,7 +197,7 @@ class OpenStruct
# data.each_pair.to_a # => [[:country, "Australia"], [:capital, "Canberra"]] # data.each_pair.to_a # => [[:country, "Australia"], [:capital, "Canberra"]]
# #
def each_pair def each_pair
return to_enum(__method__) { @table.size } unless block_given? return to_enum(__method__) { @table.size } unless block_given!
@table.each_pair{|p| yield p} @table.each_pair{|p| yield p}
self self
end end
@ -354,7 +354,7 @@ class OpenStruct
rescue NameError rescue NameError
end end
@table.delete(sym) do @table.delete(sym) do
return yield if block_given? return yield if block_given!
raise! NameError.new("no field `#{sym}' in #{self}", sym) raise! NameError.new("no field `#{sym}' in #{self}", sym)
end end
end end
@ -453,5 +453,6 @@ class OpenStruct
end end
# Other builtin private methods we use: # Other builtin private methods we use:
alias_method :raise!, :raise alias_method :raise!, :raise
private :raise! alias_method :block_given!, :block_given?
private :raise!, :block_given!
end end

View File

@ -110,6 +110,9 @@ class TC_OpenStruct < Test::Unit::TestCase
assert_equal(:foobar, o.delete_field(s) { :baz }) assert_equal(:foobar, o.delete_field(s) { :baz })
assert_equal(42, OpenStruct.new(foo: 42).delete_field(:foo) { :bug }) assert_equal(42, OpenStruct.new(foo: 42).delete_field(:foo) { :bug })
o = OpenStruct.new(block_given?: 42)
assert_raise(NameError) { o.delete_field(:foo) }
end end
def test_setter def test_setter