Skip to content

Instantly share code, notes, and snippets.

@hallelujah
Last active August 23, 2017 10:47
Show Gist options
  • Save hallelujah/07fb20635ae6815a88fd542dab5ce51b to your computer and use it in GitHub Desktop.
Save hallelujah/07fb20635ae6815a88fd542dab5ce51b to your computer and use it in GitHub Desktop.
super-hook
module PaymentDetails
def hello
puts 'Simple'
end
module Multi
def hello
puts 'Multi'
end
end
end
module HookMechanism
module_function def _hooker(obj, call_method)
case call_method
when Proc
obj.instance_exec(&call_method)
when Symbol
obj.send call_method
else
call_method
end
end
def hook(*methods, condition:)
methods.each do |method_sym|
instance_eval do
alias_method "_old_#{method_sym}", method_sym
define_method method_sym do |*args,&block|
return super(*args, &block) if HookMechanism._hooker(self, condition)
send "_old_#{method_sym}", *args, &block
end
end
end
end
end
class Account
extend HookMechanism
include PaymentDetails
hook :hello, condition: :configured?
include PaymentDetails::Multi
def initialize(configured = false)
@configured = configured
end
def configured?
@configured
end
end
Account.new(false).hello
Account.new(true).hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment