Hey all,

The Subject line may be a bad question, whether it's possible to
invoke a class method on an array of objects. But look at the code
below, and unless I am misunderstanding, that's what appears to be
going on, and yes the code does work:

class Dog
  def total_caught
    Cat.counters(:dog => self)[:caught]
  end

class Cat
def self.counters(constraints = {})
  source = constraints[:dog] ? constraints[:dog].cats : self
  CatState.keys.map.each_with_object({}) { |k, h| h[k] =
source.count_of(k)
end

  def self.count_of(state, options = {})
    since = options.delete(:since)
    options[:conditions] = ["#{state}_on > ?", since] if since

    Cat.count("#{state}_on", options)
  end

Basically, what's going on here is when the total_caught method is
invoked, it calls the Cat class method of Cat, passing into the
argument list a hash key/value pair. We assign that hash to local
variable constraints, and then check if the key dog exists, if so we
get all associated cats to the dog. Hence, it is possible for the
source local variable to hold an array of cat objects, which is the
purpose of has_many and belongs_to. But then notice we call count_of
which is a class method, so if source holds an array of objects, how
is it possible to call the count_of class method of class Cat on it?

thanks for response

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to