Nuby: determine method passed and determine the receiver that rec eived the method

Mauricio Fernández [mailto:batsman.geo@yahoo.com] aka batsman humbly replied
assisted again:

batsman@tux-chan:/tmp$ ruby e.rb
You called Dog#foo
the dog does foo
You called Dog#bar
the dog does bar
You called Dog#bar
e.rb:21:in method_missing': undefined method bar’ for
#Dog:0x401c8034 (NoMethodError)
from e.rb:19:in `method_missing’
from e.rb:42
batsman@tux-chan:/tmp$ expand -t2 e.rb

keep this secret :stuck_out_tongue:

module MethodCalledMagic
def method_added(id)
@level ||= 0
return if @level == 1
@level += 1
alias_method “real#{id}”, id
module_eval <<-EOF
def #{id}(*a,&b)
puts “You called #{self.inspect}##{id}”
real#{id}(*a,&b)
end
EOF
@level -= 1
end

def self.extend_object(obj)
obj.send :define_method, :method_missing do |id,*a|
puts “You called #{self.class}##{id}”
super id
end
super
end
end

this is what your son sees

class Dog
extend MethodCalledMagic #
end

d = Dog.new
class Dog
def foo; puts “the dog does foo” end
def bar; puts “the dog does bar” end
end

d.foo
d.bar

class Dog; undef_method :bar end
d.bar

You could also redefine Module#undef_method.

Wow. That was impressive.
Many thanks for the kind assistance, sir batsman.

kind regards -botp