Skip to content

Instantly share code, notes, and snippets.

@cjbottaro
Created June 13, 2012 22:41
Show Gist options
  • Save cjbottaro/2926951 to your computer and use it in GitHub Desktop.
Save cjbottaro/2926951 to your computer and use it in GitHub Desktop.
Adding methods to ActiveRecord::Relation to wrap results
require "spec_helper"
class RecordWrapper
def initialize(record)
@record = record
end
end
module RelationWrapping
def self.included(mod)
mod.class_eval do
attr_accessor :wrap_with_class
alias_method_chain :to_a, :wrapper
end
end
def wrap_results_with(klass)
relation = clone
relation.wrap_with_class = klass
relation
end
def to_a_with_wrapper
if not loaded? and wrap_with_class
@records = to_a_without_wrapper.collect{ |record| wrap_with_class.new(record) }
else
to_a_without_wrapper
end
end
end
ActiveRecord::Relation.send(:include, RelationWrapping)
class ActiveRecord::Base
class << self
delegate :wrap_results_with, :to => :scoped
end
end
describe "RelationWrapping" do
it "wraps records" do
users = User.wrap_results_with(RecordWrapper).limit(5)
users.all?{ |user| user.instance_of?(RecordWrapper) }.should be_true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment