From 435b224e7ec42194d974a90b89a4562ee876aafc Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 7 Aug 2015 13:35:31 -0700 Subject: [PATCH] move `valid?` conditional to the constructor use a strategy pattern to calculate the conditional in `valid?` in advance. --- actionpack/lib/action_controller/metal.rb | 32 +++++++++++++++-------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index 817339dadf..4dfd351b95 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -11,20 +11,14 @@ module ActionController # class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc: class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc: - def initialize(klass, args, only, except, block) - @only = only - @except = except + def initialize(klass, args, actions, strategy, block) + @actions = actions + @strategy = strategy super(klass, args, block) end def valid?(action) - if @only.any? - @only.include?(action) - elsif @except.any? - !@except.include?(action) - else - true - end + @strategy.call @actions, action end end @@ -38,13 +32,29 @@ def build(action, app = Proc.new) private + INCLUDE = ->(list, action) { list.include? action } + EXCLUDE = ->(list, action) { !list.include? action } + NULL = ->(list, action) { true } + def build_middleware(klass, args, block) options = args.extract_options! only = Array(options.delete(:only)).map(&:to_s) except = Array(options.delete(:except)).map(&:to_s) args << options unless options.empty? - Middleware.new(klass, args, only, except, block) + strategy = NULL + list = nil + + if only.any? + strategy = INCLUDE + list = only + elsif except.any? + strategy = EXCLUDE + list = except + end + + + Middleware.new(klass, args, list, strategy, block) end end -- GitLab