Created
January 18, 2009 18:47
-
-
Save dblack/48737 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 PerActionMiddleware | |
# DUMMY MODULE, just to get the file loaded. | |
end | |
module ActionController | |
class Base | |
class << self | |
alias _call call | |
def call(env) | |
action = env["rack.routing_args"]["action"] | |
@@app ||= prepare_mw_stack(action) | |
@@middle_stack ||= {} | |
@@app.call(env) | |
end | |
def middles | |
@middles ||= [] | |
end | |
def middle(app, *options) | |
options = options.pop || {} | |
middles.push(app) | |
Array(options[:only]).each {|action| middleware_whitelist[app] << action.to_sym } | |
Array(options[:except]).each {|action| middleware_blacklist[app] << action.to_sym } | |
end | |
def middleware_whitelist | |
@middleware_whitelist ||= Hash.new {|h,k| h[k] = [] } | |
end | |
def middleware_blacklist | |
@middleware_blacklist ||= Hash.new {|h,k| h[k] = [] } | |
end | |
def can_use_middleware?(mw, action) | |
return true if middleware_whitelist[mw].include?(action.to_sym) | |
return false if middleware_blacklist[mw].include?(action.to_sym) | |
return true if middleware_whitelist[mw].empty? | |
end | |
def prepare_mw_stack(action) | |
@@middle_stack ||= {} | |
@@middle_stack[action] ||= MiddlewareStack.new do |middleware| | |
self.middles.each do |mw| | |
middleware.use(mw) if can_use_middleware?(mw, action) | |
end | |
end | |
@@middle_stack[action].build(lambda {|env| _call(env)}) | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment