From: Hal Fulton Date: 2006-01-09T12:34:46+09:00 Subject: Re: Ideas on "Why Living Dangerous can be A Good Thing" in Ruby? Steve Litt wrote: > > I'm trying to understand this. If Model.find_by_city was never defined, how > can it know what to do? I think I'm missing some big chunk of Ruby knowledge > here. > > Are you saying that when Model.find_by_city is executed, the model looks at > the database, discovers there's a city column, and on the fly constructs a > method to search the table by city? > What you're missing is method_missing. :) When a method doesn't exist, method_missing gets called. There's a default one that raises an exception, but you can override it with any behavior you want. The name of the called method is passed in, e.g., "find_by_city"; so if you parse it and see that it has the form "find_by_X" then you can know that X is (supposed to be) a field name. Then you just handle it. A variation on this is to define the method so that next time, method_missing will not be called on that name. Makes sense? Hal