Created
November 23, 2015 17:45
-
-
Save temirov/20f1acb73227a0e14f2a to your computer and use it in GitHub Desktop.
Simple callback implementation in plain Ruby
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 BeforeCallbackable | |
module ClassMethods | |
def before(**arg) | |
@before_callbacks = {} unless defined?(@before_callbacks) | |
@before_callbacks.merge!(arg) | |
end | |
def method_added(method_name) | |
if before_callbacks.key? method_name | |
renamed_method = "before_#{method_name}".to_sym | |
fail ArgumentError, "method #{renamed_method} is already defined" if respond_to?(renamed_method) | |
define_method renamed_method, instance_method(method_name) | |
private renamed_method | |
before_method = before_callbacks.delete(method_name) | |
define_method method_name do |*args| | |
send(before_method) | |
send(renamed_method, *args) | |
end | |
end | |
end | |
private | |
attr_reader :before_callbacks | |
end | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
end | |
class TestBeforeCallback | |
include BeforeCallbackable | |
before qqq: :www | |
def qqq | |
'qqq' | |
end | |
private | |
def www | |
puts 'www' | |
end | |
end | |
TestBeforeCallback.new.qqq |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment