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

On Sun, Feb 10, 2008 at 12:21:35PM -0800, Jonas S. wrote:

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

On 10 Feb., 21:29, Gregory S. [email protected]
wrote:

  result.extend(MyCollectionMethods)
end
result

end

end

Yeah, works great =)

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

Greets
Jonas

On 10 Feb 2008, at 21:03, Jonas S. wrote:

def self.find(*args)

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

On 10 Feb., 22:09, Frederick C. [email protected]
wrote:

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)

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

On Feb 10, 2008, at 1:09 PM, Frederick C.
<[email protected]