I was playing around with implementing Rails model callbacks (after_save, before_save) etc. using alias method. All it does is it aliases the save method to save_with_callbacks. It works, except before_save has to be called after save is defined or alias keyword throws an error. I’m still in the process of understanding how Rails callbacks really works, but was wondering if there’s a way to use before_filter anywhere in the model.
module ClassMethods
def before_save
class_eval do
# old_save points to save
# save points to save_with_callbacks
alias :old_save :save
alias :save :save_with_callbacks
end
end
end
module InstanceMethods
def save_with_callbacks
@save_with_callbacks_text = 'Saving with callbacks'
old_save
end
end
class Task
extend ClassMethods
include InstanceMethods
attr_reader :save_text, :save_with_callbacks_text
def save
@save_text = 'Saving'
end
# Needs to be called after save, save_with_callbacks are defined
before_save
end
I forgot users don’t generally define ‘save’ method, but let ORM do it for you. Moved
savemethod toInstanceMethodsand that solves the problem.