Skip to content

Instantly share code, notes, and snippets.

@dgtm
Created August 27, 2012 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgtm/3489255 to your computer and use it in GitHub Desktop.
Save dgtm/3489255 to your computer and use it in GitHub Desktop.
Callback like Callbacks
module Actions
module Base
def email(args)
extend(Mail)
send(*args)
end
def statistics(m,*args)
extend(Statistics)
send(m,*args)
end
end
module Mail
def complete#(args)
puts "complete mail"
end
def auto_posted
puts "posted"
end
end
module Statistics
def complete(args)
puts "complete stats"
end
def posted(args)
puts "posted #{args}"
end
end
end
module Events
attr_accessor :wrapper
def self.extended(base)
base.wrapper = {}
base.send(:include,Triggers)
end
def method_missing(meth,*args,&block)
if @current_caller == :notification_callbacks
wrapper[meth] = block
else
super
end
end
def respond_to_missing?(m,include_private=false)
wrapper.keys.include?(m)
end
end
module Triggers
def method_missing(m,*args,&block)
current_wrapper = self.class.wrapper[m[0...-1].to_sym] #auto_posted
if m.to_s.end_with?("!") && current_wrapper.present? #auto_posted!
send(:extend, Actions::Base)
current_wrapper.call(self)
else
super
end
end
def respond_to_missing?(m,include_private=false)
current_wrapper = self.class.wrapper[m[0...-1].to_sym] #auto_posted
m.to_s.end_with?("!") && current_wrapper.present?
end
end
module CallbackChain
def notification_callbacks(&block)
send(:extend, Events)
@current_caller = __method__
instance_eval(&block)
@current_caller = nil
end
end
class A
extend CallbackChain
notification_callbacks do
completed_trip do |d|
d.email :complete
d.statistics :complete, 2
end
auto_posted do |d|
d.email :auto_posted
d.statistics :posted, 1
end
end
end
A.new.completed_trip!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment