Rail 5交换带有自定义重新加载器的ActionDispatch :: Reloader

我们有一个用例,用于在本地开发时将模拟引擎安装到进程会话,其中自定义会话中间件在请求通过时通过Net :: http请求调用模拟引擎。

当代码更改时,会触发重新加载器,并在此处调用ActiveSupport::Dependencies以开始卸载。 然后请求传递给我们的自定义会话中间件,并触发http请求。 但是,由于http请求调用可安装的引擎,它再次认为是相同的中间件,并且重新加载器再次卸载所有依赖项,这导致第一次重新加载超时。 因此,目标是能够跳过第二个请求的重新加载。

我在这里向ActionDispatch::Reloader添加了以下代码,它完全符合我的要求。

 class Reloader < Executor def initialize(app, executor) super(app, executor) end def call(env) request = ActionDispatch::Request.new(env) return @app.call(env) if skip_request?(request) super(env) end def skip_request?(request) request.path_info.start_with?('/session') end end 

然后我想让这个更干净的想法完全把它拉出来一个模块,然后从初始化器中做这样的交换

 app.config.middleware.swap(::ActionDispatch::Reloader, MyModule::CustomReloaderMiddleware) 

这是模块

 require 'action_dispatch' module MyModule class CustomReloaderMiddleware < ActionDispatch::Executor def initialize(app, executor) @app, @executor = app, executor end def call(env) request = ActionDispatch::Request.new(env) return @app.call(env) if skip_request?(request) super(env) end def skip_request?(request) request.path_info.start_with?('/session') end end end 

但我遇到了几个问题。

Uncaught exception: wrong number of arguments (given 1, expected 2)当我启动服务器时, MyModule initialize Uncaught exception: wrong number of arguments (given 1, expected 2) 。 然后我尝试了以下内容

 #1 def initialize(app, executor = nil) @app, @executor = app, executor end #2 def initialize(app, executor = nil) @app, @executor = app, ActiveSupport::Reloader end 

他们两个都正确启动服务,我看到请求通过这个中间件,但它没有重新加载代码..所以我想知道什么是使用自定义重新加载器交换ActionDispatch :: Reloader的正确方法?

您需要将中间件的附加参数传递给swap调用:

 app.config.middleware.swap(::ActionDispatch::Reloader, MyModule::CustomReloaderMiddleware, app.reloader) 

这是第一次添加 ActionDispatch::Reloader时给出的相同参数 – 它是应用程序的重新加载器,它是AS :: Reloader的一个更具体配置的子类(所以你在正确的轨道上)。