jonas_s
1
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
jonas_s
2
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
jonas_s
3
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
jonas_s
4
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
jonas_s
5
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
jonas_s
6
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]