From aaece34e8b1e5ad66ba91ce68af09a1cd146052b Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Thu, 4 Jun 2020 17:13:59 +0800 Subject: [PATCH] DEV: Update rails_failover so that we can move middleware up the stack. --- Gemfile.lock | 2 +- config/initializers/200-first_middlewares.rb | 4 +++ lib/freedom_patches/middleware_stack.rb | 38 ++++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 lib/freedom_patches/middleware_stack.rb diff --git a/Gemfile.lock b/Gemfile.lock index baa304a8ecd..56fa08db25e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,6 +1,6 @@ GIT remote: https://github.com/discourse/rails_failover - revision: e9893a3920809c9a1bca4f7ae07b7243b2cd127e + revision: 19a40ef42cb051c56d2679940ec5f00a436e670b specs: rails_failover (0.4.0) activerecord (~> 6.0) diff --git a/config/initializers/200-first_middlewares.rb b/config/initializers/200-first_middlewares.rb index 14432d8b9a1..ab53806254f 100644 --- a/config/initializers/200-first_middlewares.rb +++ b/config/initializers/200-first_middlewares.rb @@ -25,3 +25,7 @@ if Rails.configuration.multisite Rails.configuration.middleware.unshift RailsMultisite::Middleware, RailsMultisite::DiscoursePatches.config Rails.configuration.middleware.delete ActionDispatch::Executor end + +if ENV["ACTIVE_RECORD_RAILS_FAILOVER"] + Rails.configuration.middleware.move_after(RailsMultisite::Middleware, RailsFailover::ActiveRecord::Middleware) +end diff --git a/lib/freedom_patches/middleware_stack.rb b/lib/freedom_patches/middleware_stack.rb new file mode 100644 index 00000000000..bf9d76f41a6 --- /dev/null +++ b/lib/freedom_patches/middleware_stack.rb @@ -0,0 +1,38 @@ +# TODO: Remove once we upgrade to Rails 6.1 +# Copied implementation from https://github.com/rails/rails/pull/38169 +module ActionDispatch + class MiddlewareStack + def move(target, source) + source_index = assert_index(source, :before) + source_middleware = middlewares.delete_at(source_index) + + target_index = assert_index(target, :before) + middlewares.insert(target_index, source_middleware) + end + alias_method :move_before, :move + + def move_after(target, source) + source_index = assert_index(source, :after) + source_middleware = middlewares.delete_at(source_index) + + target_index = assert_index(target, :after) + middlewares.insert(target_index + 1, source_middleware) + end + end +end + +module Rails + module Configuration + class MiddlewareStackProxy + def move_before(*args, &block) + @delete_operations << -> middleware { middleware.send(__method__, *args, &block) } + end + + alias :move :move_before + + def move_after(*args, &block) + @delete_operations << -> middleware { middleware.send(__method__, *args, &block) } + end + end + end +end