Forum: Ruby on Rails Adding methods to an array of AR objects

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
73c04e9ef9ca435c5b19a2e765ae6d20?d=identicon&s=25 Max Williams (max-williams)
on 2008-11-07 11:14
I have some methods that i want to be able to call on any collection of
ActiveRecord objects.  What's the 'right' way to set this up?  I don't
want to just monkey patch Array as it's specific to an AR array.

Thanks
max
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-11-07 11:22
(Received via mailing list)
On 7 Nov 2008, at 10:14, Max Williams wrote:

>
> I have some methods that i want to be able to call on any collection
> of
> ActiveRecord objects.  What's the 'right' way to set this up?  I don't
> want to just monkey patch Array as it's specific to an AR array.

If you extend AssociationCollection you'll be able to it on any
association (eg some_object.customers.foo). There is no proxy object
for the result of Foo.find though (I have an experimental plugin that
does do this). You could wrap the result of finds in a proxy (as i
did) or you could add singleton methods to the results of find
(ie

class << ActiveRecord::Base
   def find_with_extra_methods(*args)
     results = find_without_extra_methods(*args)
     results.extend(SomeModuleOfExtraMethods) if results.is_a? Array
     results
   end

   alias_method_chain :find, extra_methods
end
This topic is locked and can not be replied to.