0

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 ?

tereško
  • 58,060
  • 25
  • 98
  • 150
Rafal
  • 2,576
  • 2
  • 18
  • 13

1 Answers1

1

This should works. You have a proxy instance and extending by module.

query = Query.limit(10).all

module SomeModule
  def average_size_x
  end

  def average_size_y
  end
end

query.extend(SomeModule)

query.average_size_y
query.average_size_y
Leszek Andrukanis
  • 2,114
  • 2
  • 19
  • 30
  • ok, this is good, but requires to call the extend every time I do a query. Any way to set this on the model Query so that the extended methods are available on every query that is done on this Model ? – Rafal Jan 19 '13 at 17:34
  • 1
    @Rafal what about extending Query in an initializer? It will be applied to all models, but that is negligible overhead. See here for an example: http://stackoverflow.com/questions/2328984/rails-extending-activerecordbase – Damien Roche Jan 19 '13 at 18:13