ruby metaprogramming - yield block not working in dynamically added method
-
05-07-2019 - |
Question
I'm working on extending the NotAMock framework for stubbing methods in rspec, and getting the stubs to yield to a methods block.
The code in this Gist works perfectly when I code it on my own (which is done-up to resemble how NotAMock stubs methods).
but when I incorporate the object.instance_eval... code into the NotAMock framework, the "block_given?" always returns false and I can never get my yield to work because of that. The method is added correctly, and I can call the stubbed method... but it will not recognize the block that i pass to the method, from the NotAMock stubbed version.
To see how i have incorporated this code into the NotAMock framework, go to my clone of NotAMock and check out the "add_hook" method in the private methods.
I know this is a bit much to ask... i'm hoping to find some guidance. it's been driving me nuts all day.
Solution 2
Turns out the issue is unrelated to the code that i linked to... the NotAMock framework is doing some additional method re-definition that is causing my issue. I've narrowed the issue down to one specific line of code, and am working out how to fix it now.
OTHER TIPS
I'm not even sure this is possible. New Procs don't even recognize blocks.
proc = Proc.new do
if block_given?
yield
else
puts "Not in a block"
end
end
proc.call { puts "In a block"} # => puts Not in a block
Ruby 1.9 is supposed to allow blocks to take &block as parameters. But I don't know if that will work or even if it will allow conditional blocks.