From 52369fc545c458efb2fa7e8ca183b119252bb4f9 Mon Sep 17 00:00:00 2001 From: Marc-Andre Lafortune Date: Mon, 14 Jun 2021 10:07:51 -0400 Subject: [PATCH] [lib/ostruct] Allow overriding of `block_given?` --- lib/ostruct.rb | 7 ++++--- test/ostruct/test_ostruct.rb | 3 +++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/ostruct.rb b/lib/ostruct.rb index a4e7b446db..eef1d5c861 100644 --- a/lib/ostruct.rb +++ b/lib/ostruct.rb @@ -197,7 +197,7 @@ class OpenStruct # data.each_pair.to_a # => [[:country, "Australia"], [:capital, "Canberra"]] # 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} self end @@ -354,7 +354,7 @@ class OpenStruct rescue NameError end @table.delete(sym) do - return yield if block_given? + return yield if block_given! raise! NameError.new("no field `#{sym}' in #{self}", sym) end end @@ -453,5 +453,6 @@ class OpenStruct end # Other builtin private methods we use: alias_method :raise!, :raise - private :raise! + alias_method :block_given!, :block_given? + private :raise!, :block_given! end diff --git a/test/ostruct/test_ostruct.rb b/test/ostruct/test_ostruct.rb index f8d184b011..d2aad4428f 100644 --- a/test/ostruct/test_ostruct.rb +++ b/test/ostruct/test_ostruct.rb @@ -110,6 +110,9 @@ class TC_OpenStruct < Test::Unit::TestCase assert_equal(:foobar, o.delete_field(s) { :baz }) 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 def test_setter