From: James Britt Date: 2005-11-29T15:39:20+09:00 Subject: Re: Rails Web Service: Convert Parameter to Class Method Call? Craig wrote: > Thanks for the quick reply. I'm just starting with both Ruby and Rails, > so this was very helpful. How would you execute the result of the > method_missing call? What should I do to make sure this is secure? > Once method_missing has teased apart the request, you have few options. The example just created a string of code, so you could just pass that to eval(). Not recommend expect perhaps to test some code to see that things are perhaps working up to that point. Since you decompose the name of the missing method into a class name and a request, you can get a reference to the class then try to invoke request as a class method. class Finder def method_missing( sym, *args ) if sym.to_s =~ /(\w+)_find$/ klass = $1.capitalize cls = Object.const_get( klass ) return cls.find elsif sym.to_s =~ /(\w+)_find_by_([a-z_]+)/ klass = $1.capitalize cls = Object.const_get( klass ) params = $2 cls.send( "find_by_#{params}", args ) else super end end end If you prefer to create object instances, then first call 'new' on the class reference: def method_missing( sym, *args ) if sym.to_s =~ /(\w+)_find$/ klass = $1.capitalize cls = Object.const_get( klass ) obj = cls.new return obj.find elsif sym.to_s =~ /(\w+)_find_by_([a-z_]+)/ klass = $1.capitalize cls = Object.const_get( klass ) params = $2 obj = cls.new obj.send( "find_by_#{params}", args ) else super end end Note that all sorts of error handling has been omitted here. You may want to take more precautions in what classes are created and what methods get invoked. For example you could first check that the extracted class name is contained in an 'allowed objects' list before instantiation anything. Hope this helps, James Britt -- http://www.ruby-doc.org - Ruby Help & Documentation http://www.artima.com/rubycs/ - Ruby Code & Style: Writers wanted http://www.rubystuff.com - The Ruby Store for Ruby Stuff http://www.jamesbritt.com - Playing with Better Toys http://www.30secondrule.com - Building Better Tools