Craig wrote: > I'm trying to write a method for a web service that will find objects > from a user specified table, i.e. find all Widgets added in last 7 > days, or find all Whatsits whose name starts with Q. > > I could right a separate method for each table calling i.e. > Widget.find() or Whatsit.find(), but what I'd like to do is have a > single interface that lets me call something like > user_specified_table.find() where user_specified_table is a string > equal to either Widget or Whatsit. > > How can I do this? Is there an entirely different way of doing this > that I should be looking at? > method_missing is your best friend. Oh, and 'send', too. Fast attempt at an example: #!/usr/local/bin/ruby class Finder def method_missing( sym, *args ) if sym.to_s =~ /(\w+)_find$/ klass = $1.capitalize "#{klass}.find" elsif sym.to_s =~ /(\w+)_find_by_([a-z_]+)/ klass = $1.capitalize params = $2 "#{klass}.find_by_#{params}" else super end end end if __FILE__ == $0 require 'test/unit' class TC_FOO < Test::Unit::TestCase def setup @f = Finder.new end def test_00 res = @f.whatsit_find assert_equal( "Whatsit.find" , res ) end def test_01 res = @f.widget_find_by_name assert_equal( "Widget.find_by_name" , res ) end def test_02 assert_raise( NoMethodError ){ @f.widget_fetch_me_coffee } end end end James -- 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