Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ActiveModel::Callbacks to work with ActiveResource

I am trying to get ActiveModel::Callbacks to work with ActiveResource (specifically after_initialize) for a Rails 3 app, but I can't seem to get it to work. I don't get any errors, but the callback method is never executed.

Here is a snippet of code

class User < ActiveResource::Base
  extend ActiveModel::Callbacks
  define_model_callbacks :initialize, :only => :after

  after_initialize :update_info

  def update_info
    puts 'info'
  end 
end

For some reason, the update_info is never executed. Anyone have any idea how to get this to work?

like image 588
gmoniey Avatar asked Feb 14 '12 00:02

gmoniey


1 Answers

In case anyone is interested, I re-read the documentation on this, and what I thought was an explanation of how the code worked under the covers, turned out to be a requirement which stated that I needed to override the method I was adding callbacks to:

def initialize(attributes = {}, persisted = false)
  run_callbacks :initialize do
    super(attributes, persisted)
  end
end

This seems incredibly counter-intuitive to me, as it expects you to track down the signature of the existing method, overwrite it, and add the callback functionality. I hope I am missing something here, and simply making a mistake, but I haven't gotten any other solution to work.

Anyways, here is a monkey patch to provide this callback to all AR classes:

module ActiveResource
  class Base    
    extend ActiveModel::Callbacks
    define_model_callbacks :initialize, :only => :after

    def initialize_with_callback(attributes = {}, persisted = false)
      run_callbacks :initialize do
        initialize_without_callback(attributes, persisted)
      end
    end
    alias_method_chain :initialize, :callback
  end
end
like image 183
gmoniey Avatar answered Oct 11 '22 14:10

gmoniey