Created
January 28, 2009 17:04
-
-
Save jasoncale/54057 to your computer and use it in GitHub Desktop.
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
class DispatchHook | |
class << self; attr_accessor :dispatch_hooks; end | |
@dispatch_hooks = [] | |
attr_accessor :actions | |
def self.register(*actions, &block) | |
returning(self.new(actions, block)) do |hook| | |
dispatch_hooks << hook | |
end | |
end | |
def self.dispatch_for(action) | |
#return if action.blank? | |
dispatch_hooks.each {|hook| hook.try_for(action) } | |
nil | |
end | |
def try_for(action) | |
@hook.call if (@actions.include?(action) || actions.include?("all")) | |
end | |
protected | |
def initialize(actions, block) | |
@actions = actions.flatten | |
@hook = block | |
end | |
end | |
actions = %w(love dogs bone) | |
DispatchHook.register(actions) { puts "this does them all" } | |
DispatchHook.register("dogs") { puts "this is the dog one" } | |
DispatchHook.dispatch_for("love") #=> "this does them all" | |
DispatchHook.dispatch_for("none") | |
DispatchHook.dispatch_for("dogs") #=> "this does them all" & "this is the dog one" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment