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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With