On Sat, Jan 24, 2004 at 07:47:20PM +0900, "Pe?a, Botp" wrote:
> I am a newbie, and am trying to build a lesson plan for learning oop for
> beginners like me and non-programmers -and my son fits the bill. I hope to
> finish it before summer so that me and my son can learn together.
> 
> Reading Dave's PickAxe, I got to the portion of explaining to myself the
> concept of receiver and method. Hoping that I'd simplify things to learn
> first, I started off w a definition of a class without any methods defined
> (in my example, class Dog). I would then instantiate an object of that kind
> of class and bombard it with any methods I like.
> 
> However, I was stuck on "how does one know what methods were passed". I want
> to do this so I can say (especially to my son), "See son, it (the dog) got
> what you asked for. Next, we will now let it do what we asked..."... I
> thought this was possible since there is a method_missing() method wc knows
> the method passed (-unfortunately it is missing :-)..

You could simulate that with some meta-programming magic involving
alias_method and method_added, but I wouldn't show that code to your
son ;)

batsman@tux-chan:/tmp$ expand -t2 e.rb

# keep this secret :P
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
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

batsman@tux-chan:/tmp$ ruby e.rb
You called Dog#foo
the dog does foo
You called Dog#bar
the dog does bar


-- 
 _           _                             
| |__   __ _| |_ ___ _ __ ___   __ _ _ __  
| '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ 
| |_) | (_| | |_\__ \ | | | | | (_| | | | |
|_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
	Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

And Bruce is effectively building BruceIX
	-- Alan Cox