I want to extend the Array returned from a query to add new methods.
Lets assume I have a model Query and it has a few calculated attributes size_x, size_y ...
In my controller, I retrieve a few queries
@queries = Query.limit(10).all
Now @queries becomes an Array. I would like to extend the Array with 2 methods
@queries.average_size_x
And
@queries.average_size_y
I am looking for a neat solution that will enhance the Array returned with those 2 methods without adding it to the global Array class. Is there any way to do that ?
Here are some things I tried:
- Redefining the self.find method
This only works if I change my query to the old syntax
Query.find(:all, :limit => 5)
extending the relation
Query.limit(10).extending(QueryAggregator)
This works if I don't call the all
method as the object is an ActiveRecord relation but onceall
is called, the methods average_size_x
is not available.
The only option I see is to extend Array class and add the methods there, but it might be irrelevant for other Models...
Any suggestions ?