From: "David A. Black" Date: 2005-04-27T11:17:50+09:00 Subject: Re: rewriting method_missing Hi -- On Wed, 27 Apr 2005, Tyler Pirtle wrote: > I'm not even sure if this would be possible but I think I need some > help. In the spirit of the method_missing hall of fame, I want to be > able to do..sort of a nested method_missing. > > how can i get at > Instance.bogus_member1.bogus_member2 > > bogus_member2 through the class of Instance? > Or better yet, suppose bogus_member1 returned an object, how could I > get at bogus_member2 through the class of the object of bogus_member1? > > I've tried just using method_missing statements in 2 different > classes, but Ruby seems to want to perform the last method first - and > because bogus_member1 doesn't exist its trying to call something from > NilClass. Ruby goes from left to right, so you'll get the nil message if Instance is returning nil, or if Instance.bogus_member1 is returning nil. > > Ideally, what will happen is that bogus_member1 will be an object that > will be instantiated based on its own criteria - for example, suppose > every day of school you had a new teacher > > School.MrSmith.homework > but the next day > School.MrsJones.homework > > MrSmith & MrsJones are objects that get instantiated as Teachers based > on their criteria - > > class School > def method_missing(*args) > ... > Teachers.new(args[0]) > end > > What i'd like to do is at that same line... > > Teacher.new(args[0]).send(args[1..-1])) > > But it seems as if Ruby is going in the other direction.(end to start) I'm not clear on what the criteria or args are. What exactly are you trying to send to the new Teacher object? > What can I do? I don't know if this will help, but here's some playing around with this: class Teacher attr_accessor :name def initialize(name) self.name = name end def homework "This is an assignment from #{name}..." end end class School class << self def method_missing(*args) Teacher.new(args[0]) end end end puts School.MrSmith.homework puts School.MrsJones.homework Output: This is an assignment from MrSmith... This is an assignment from MrsJones... I don't know that this will scale very well or offer you much functionality, though. It looks like a case of trying to use method-call syntax (the dot) for argument semantics (passing objects to each other), which may be asking too much of the humble dot. David -- David A. Black dblack@wobblini.net