Active Resource Callbacks

Posted on 27 Aug 2008

It looks like work is still on-going to extract functionality common to Active Record and Active Resource into a new Active Model library. Excellent. But I wanted to add a couple of callbacks to Active Resource and I wanted to do it quickly. Thankfully, someone much smarter than me has already extracted callbacks from Active Record, so getting something working was pretty straight forward.

module ActiveResource
  module Callbacks
    CALLBACKS = %w( after_save after_destroy )
    
    def self.included(base)
      [:save, :destroy].each do |method|
        base.send :alias_method_chain, method, :callbacks
      end
      
      base.send :include, ActiveSupport::Callbacks
      base.define_callbacks *CALLBACKS
    end
    
    def save_with_callbacks
      returning save_without_callbacks do
        run_callbacks(:after_save) unless new?
      end
    end
    
    def destroy_with_callbacks
      returning destroy_without_callbacks do
        run_callbacks(:after_destroy)
      end
    end
  end
end

ActiveResource::Base.send :include, ActiveResource::Callbacks