This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def method_added(method) | |
if !setting_callback | |
redefine_method(method) if is_a_callback?(method) | |
end | |
end | |
def redefine_method(original_method) | |
@setting_callback = true | |
original = instance_method(original_method) | |
define_method("#{original_method}_with_callbacks".to_sym) do |*args, &block| | |
trigger_callbacks(original_method, :before) | |
return_val = original.bind(self).call(*args, &block) if original | |
trigger_callbacks(original_method, :after) | |
return_val | |
end | |
alias_method original_method, "#{original_method}_with_callbacks".to_sym | |
@setting_callback = false | |
end |
Here is what the callback code looks like now. I feel like it is very readable and easy to comprehend:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module CallbackPureRuby | |
def self.included(klass) | |
klass.extend ClassMethods | |
klass.initialize_included_features | |
end | |
module ClassMethods | |
def initialize_included_features | |
@callbacks = Hash[:before, {}, :after, {}] | |
class << self | |
attr_accessor :callbacks | |
attr_accessor :setting_callback | |
end | |
end | |
def store_callbacks(type, method_name, *callback_methods) | |
callbacks[type][method_name] = callback_methods | |
if !setting_callback | |
prepend_method(method_name) | |
end | |
end | |
def method_missing(method, *args, &block) | |
if method.to_s =~ /^before|after$/ | |
store_callbacks(method, *args) | |
else | |
super | |
end | |
end | |
def prepend_method(original_method) | |
@setting_callback = true | |
save_with_callbacks = Module.new do | |
define_method(original_method) do |*args, &block| | |
trigger_callbacks(original_method, :before) | |
return_val = super() | |
trigger_callbacks(original_method, :after) | |
return_val | |
end | |
end | |
prepend save_with_callbacks | |
@setting_callback = false | |
end | |
end | |
def trigger_callbacks(method_name, callback_type) | |
unless self.class.callbacks[callback_type][method_name].nil? | |
self.class.callbacks[callback_type][method_name].each{ |callback| __send__ callback } | |
end | |
end | |
end |