Is there any way to get hold of the invoked object inside the block thats being called. For instance, is there any way for the blocks to get access to the scope of the method batman
or the class SuperHeros
class SuperHeros
attr_accessor :news
def initialize
@news = []
end
def batman task
puts "Batman: #{task} - done"
yield "feed cat"
@news << task
end
end
cat_woman = lambda do |task|
puts "Cat Woman: #{task} - done"
# invoker.news << task
end
robin = lambda do |task|
puts "Robin: #{task} - done"
# invoker.news << task
end
characters = SuperHeros.new
characters.batman("kick Joker's ass", &cat_woman)
characters.batman("break Bane's bones", &robin)
The simplest way to get the receiver object inside a block is assigning the object to an instance variable.
This example illustrate more clearly how the lambdas cat_woman and robin can access to attributes of the receiver objects of blocks:
The output will be:
You can use something similar to Instance eval with delegation pattern, used - for example - in Savon gem:
In this approach, when you call method (with implicit receiver) inside block passed into
batman
method, it's called in the context ofSuperHeros
instance. If there is no such method available, the call goes (throughmethod_missing
) to original blockself
.