Created
November 1, 2011 13:49
-
-
Save igravious/1330528 to your computer and use it in GitHub Desktop.
Generalized filters in Camping
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
# | |
# include the CampingHooks module in TheApp | |
# | |
module CampingHooks | |
module ClassMethods | |
def set_hook_key(k) | |
@hooks ||= {} | |
@hooks[k] ||= [] | |
end | |
def set_hook_value(k, v) | |
set_hook_key(k) | |
@hooks[k] << v | |
end | |
def get_hooks | |
@hooks ||= {} | |
end | |
def hook(hook_pair, &block) | |
hook_sym = hook_pair.keys.first | |
hook_actions = hook_pair.values.first | |
instance_eval <<-EOT | |
def #{hook_sym}(actions, &block) | |
actions = [actions] unless actions.respond_to?(:each) | |
#binding.pry | |
actions.each do |action| | |
set_hook_value(:#{hook_sym}, [action, block]) | |
end | |
end | |
EOT | |
send(hook_sym, hook_actions, &block) | |
end | |
end # ClassMethods | |
def self.included(mod) | |
mod.extend(ClassMethods) | |
end | |
def run_filter(sym) | |
o = self.class.to_s.split("::") | |
app = Object.const_get(o.first) | |
filters = app.get_hooks | |
app.set_hook_key(sym) | |
filters[sym].each do |filter| | |
if (filter[0].is_a?(Symbol) && (filter[0] == o.last.to_sym || filter[0] == :all)) || | |
(filter[0].is_a?(String) && /^#{filter[0]}\/?$/ =~ @env.REQUEST_URI) | |
self.instance_eval(&filter[1]) | |
end | |
end | |
end | |
def service(*a) # params to controllers, ids n stuff | |
override_self = catch(:halt) do | |
run_filter(:before_service) | |
override_self = super(*a) | |
run_filter(:after_service) | |
override_self | |
end | |
override_self | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment