Adding methods to Collections

Hello,

I´m planning to create a room managaement system in Rails. I have a collection of rooms, like this:

@rooms = Room.find :all

Then I want to write:

@rooms.to_svg # (or any other method name)

to convert this collection of rooms into SVG. Now the question: Where do I have to define those methods? I could write

def @rooms.to_svg

but that would be only for this collection; if I do Room.find :blah, I want to be able to do the same thing.

Thanks, Jonas

Hello,

I?m planning to create a room managaement system in Rails. I have a collection of rooms, like this:

@rooms = Room.find :all

Then I want to write:

@rooms.to_svg # (or any other method name)

to convert this collection of rooms into SVG. Now the question: Where do I have to define those methods? I could write

def @rooms.to_svg

but that would be only for this collection; if I do Room.find :blah, I want to be able to do the same thing.

class Room < ActiveRecord::Base   module MyCollectionMethods     def to_svg       #...     end   end

  def self.find(*args)     result = super(*args)     if args[0] == :all || Array === args[0]       result.extend(MyCollectionMethods)     end     result   end

end

Note: off the cuff and untested

Thanks, Jonas

--Greg

Yeah, works great =)

But why the check if args[0] == :all || Array === args[0] ?

Greets Jonas

class Room < ActiveRecord::Base module MyCollectionMethods    def to_svg      #...    end end

def self.find(*args)    result = super(*args)    if args[0] == :all || Array === args[0]      result.extend(MyCollectionMethods)    end    result end

end

Yeah, works great =)

But why the check if args[0] == :all || Array === args[0] ?

So that you don't add the collection methods when find is not
returning an Array (ie if you're doing find(some_id) or find :first)

Fred

Ah, OK. Thanks!

--Jonas

We could do:

Unless result.is-array Result.extend End Result

Any thoughts?

Http://www.rubyplus.org Free Ruby & Rails screencasts