0

I've taken over porting a large application from rails 2 to rails 3. The new application uses Datamapper as its ORM (decision taken prior to me coming to the project, so I can't change this).

The old application used the activerecord "after_find" callback quite extensively;

class Foo < ActiveRecord::Base
  after_find :bar
  def bar
    #This would be called after an object was "found"
  end
end

I need to implement this in Datamapper, but I can't just monkey patch the find methods because datamapper uses composition rather than inheritence;

class Foo
  include Datamapper::Resource
end

so if I monkey patched the find methods, there would be no way of me calling the original method! Could anyone point me in the right direction?

== EDIT ==

I have tried including the following:

module ClassMethods

  def after_find(meth)
    class << self
      alias_method :orig_first, :first
      def first(*args, &block)
        puts "XXX FOUND THE FIRST"
        orig_first args, &block
      end
    end
  end
end

But this just sends the code into an infinite loop (constantly printing "XXX FOUND THE FIRST")

Mikey Hogarth
  • 4,672
  • 7
  • 28
  • 44
  • 1
    I can't find a connection between the problem and the solution you added. So you are implementing the `after_find` method because it is not present in data-mapper? And why exactly are you aliasing `first`? Whatever you are trying to do, you can use `alias_method_chain`. be aware, that you are working on a class-level. you probably don't want to do that within a method call, because it will be executed each time the method is called. that is quite often in development mode. Also see this http://ansaurus.com/question/803532-implementing-an-activerecord-before_find – phoet Jan 07 '14 at 13:14
  • I used "first" as a kind of find (the solution wasn't implemented entirely) - the idea was basically to override "first", creating a backup of it in the "orig_first" method, and then do what I wanted to do followed by a call to the original method but it was largely just guesswork at that stage. I've done a bit more research now (thanks to your link) and found this: http://erniemiller.org/2011/02/03/when-to-use-alias_method_chain/ which explains it all really nicely - will have another crack at it in the morning. – Mikey Hogarth Jan 07 '14 at 16:47

0 Answers0