Ccreating methods on the fly / counting distinct field values

Hi,

I'm pretty new to ruby and rails, so apologies if this has been covered
before (I couldn't find a thread on it).

I want to retrieve a count of records held in the DB for every distinct
value of an attribute.

E.g. given a class Address with a postcode field, I would like to retrieve
an array of ValueCount objects. The ValueCount object would hold the value
retrieved from the db and the number of records which hold it.

I've written a class specific method which does this:
selects all occurrences of an object with
  ActiveRecord.find(:all, :select => "DISTINCT postcode")
then for each value issues a
  ActiveRecord.count(:all, :conditions => {:postcode => postcode}) call.

I realise this is rather clumsy and could probably be done in a better way,
but it does work.

However, my problem is that I want to write a method to create this sort of
call on the fly.
E.g.
  distinct_count :postcode
would create a distinct_count_postcode method which achieves all of the
above for the postcode field. I can then call this in any of my model
classes.

So, can anyone point me in the direction of a tutorial for creating methods
on the fly using symbols?

If anyone can show a better way to perform the ActiveRecord value_count
logic, that would be great too :slight_smile:

Thanks,
Pat

Look for tutorials dealing with mixins or plugins.