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.

Ryan Bates 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.

https://github.com/ernie/squeel/blob/master/lib/squeel/adapters/active_record.rb

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:

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