Rafal
Rafal

Reputation: 2576

Extend the Array returned from a query in Rails - Refactoring

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:

This only works if I change my query to the old syntax

Query.find(:all, :limit => 5)

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 ?

Upvotes: 0

Views: 347

Answers (1)

Leszek Andrukanis
Leszek Andrukanis

Reputation: 2125

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

Upvotes: 1

Related Questions