Alex Rivera | Logout

How do you make a method apply to a collection of ActiveRecord objects

Asked 2008-10-22T00:59:31.197
9

Currently, if I want to apply a method to a group of ActiveRecord objects, I have to structure the call like so:

messages = Message.find(:all)
csv = Message.to_csv(messages)

How can I define the method so it's structured like so?

messages = Message.find(:all)
csv = messages.to_csv

This is the current model code:

require 'fastercsv'
class Message < ActiveRecord::Base
  def Message.to_csv(messages)
    FasterCSV.generate do |csv|
      csv << ["from","to", "received"]
      for m in messages
        csv << [m.from,m.to,m.created_at]
      end
    end
  end
end
Edit
Report

1 Answer

0

You could define the method directly on the messages object itself, but if you do that, the method would only be available to that specific instance:

def messages.to_csv()

   FasterCSV.generate do |csv|
     csv << ["from", "to", "received"]
     self.each { |m| csv << [m.from, m.to, m.created_at] }   
   end

end

Then you could call it like so:

messages.to_csv

I'm a Ruby newbie, so I'm not sure if this is idiomatic Ruby or not: that is, I'm not sure how common or accepted it is to define new methods directly on object instances, I only know it's possible ;-)

answered 2008-10-22T01:35:52.480

Your Answer