Hook into ActiveRelation?

I want to define a method on ActiveRelation that works like the
following…

users = User.where(…).wrap_results_with(UserDelegator)

which would be equivalent to:

users = Users.where(…).collect{ |user| UserDelegator.new(user) }

How/where would I define wrap_results_with?

I just need a point in the right direction to get my foot in the door.
Thanks.

On Wed, Jun 13, 2012 at 5:38 PM, Christopher J. Bottaro <
[email protected]> wrote:

I just need a point in the right direction to get my foot in the door.
Thanks.

Ryan B. showed how to do all that in a recent pro Railscast.

Take a look at this code from squeel that add methods to active record
relations.

look at lines with ActiveRecord::Relation.send :include, module_methods
you
can load your methods into ActiveRecord::Relation with an initializer
like
this

ActiveSupport.on_load :active_record do
ActiveRecord::Relation.send(:include, your_module)end

is nice how the styling got copied too for the code snippets. XD

Radhames Brito wrote in post #1064485:

On Wed, Jun 13, 2012 at 5:38 PM, Christopher J. Bottaro <
[email protected]> wrote:
Take a look at this code from squeel that add methods to active record
relations.

Awesome, thanks! Heh, since posting though, I just opened up the
activerecord gem and figured it out. Here’s how I did it:

– C

From Ruby Syntax point of view, you could write something like this:

[1,2,3].wrap_results_with(UserDelegator, &p)

where the method looks like:

def block_wrap_with(klass, &block)
map do |a|
result = yield a, klass
end
end

and

p = lambda { |m, klass| klass.new(m) }

possibly, you could put the block definition inside the method

def block_wrap_with(klass)
p = lambda { |m, klass| klass.new(m) }
map do |a|
p.call(a, klass)
end
end

On Wed, Jun 13, 2012 at 11:38 PM, Christopher J. Bottaro