Hi --

On Mon, 27 Jul 2009, Hunt Hunt wrote:

> hi friends,
>
> I hav a query to ask...
>
> class A
>  def self.go
>    return A.new
>  end
>
>  def method_missing( method_name)
>   puts in methodmissing

If you don't get a syntax error there, you've got a very strange
version of Ruby installed :-)

>   puts " #{method_name} method is missing"
>  end
>
> end
>
> a = A.go
> a.name # a.name will print in method missing & name method is missing.
>
>
> upto here it is working.
>
> now when i create an object
>
> A.new.add # it also prints in method missing & add method is missing.
>
> which i don't want I want that class method go which return an instance
> should call method_missing not an instance which is created
> by A.new
>
> how am i supposed to do?

Ruby provides a full toolkit for making two objects of the same class
behave differently from each other. (In fact, classes are really just
a convenient way to save writing code when you've got multiple objects
that happen to share behaviors.)

Here's what you can do:

class A
   module SpecialMethodMissing
     def method_missing( method_name)
       puts "in methodmissing"
       puts " #{method_name} method is missing"
     end
   end

   def self.go
     A.new.extend(SpecialMethodMissing)
   end
end

I'm using extend to add the special method_missing behavior (via the
module) to that one instance.

Depending on the structure of the rest of your program, you might want
to subclass A and have a different class whose instances have that
special method_missing.


David

-- 
David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com
Q: What's the best way to get a really solid knowledge of Ruby?
A: Come to our Ruby training in Edison, New Jersey, September 14-17!
    Instructors: David A. Black and Erik Kastner
    More info and registration: http://rubyurl.com/vmzN