Getting ActiveModel::Callbacks to work with ActiveResource
Asked Answered
P

1

7

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?

Parodic answered 14/2, 2012 at 0:12 Comment(0)
P
7

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
Parodic answered 14/2, 2012 at 9:6 Comment(1)
This is rather disappointing, but it appears you are right. github.com/rails/rails/blob/master/activemodel/lib/active_model/…Topdress

© 2022 - 2024 — McMap. All rights reserved.