# Adding methods to an array of AR objects

**URL:** <https://www.ruby-forum.com/t/adding-methods-to-an-array-of-ar-objects/152779>\
**Category:** Rails\
**Created:** [November 7, 2008, 11:14am UTC](https://www.ruby-forum.com/t/adding-methods-to-an-array-of-ar-objects/152779 "2008-11-07T11:14:08Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [November 7, 2008, 11:14am UTC](https://www.ruby-forum.com/t/adding-methods-to-an-array-of-ar-objects/152779/1 "2008-11-07T11:14:08Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![cmaxvv](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/85f322/32.png) [@cmaxvv](https://www.ruby-forum.com/u/cmaxvv)\
**Post date:** [November 7, 2008, 11:22am UTC](https://www.ruby-forum.com/t/adding-methods-to-an-array-of-ar-objects/152779/2 "2008-11-07T11:22:18Z")

</div>

On 7 Nov 2008, at 10:14, Max W. 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
