在中间件中使用 Rails.application.routes.recognize_path 会破坏应用程序

Using Rails.application.routes.recognize_path inside middleware breaks the app

下一个中间件导致 Rails 应用无法加载资产

class Wtf
  def initialize(app)
    @app = app
  end

  def call(env)
    request = Rack::Request.new(env)
    # next line is causing all troubles
    Rails.application.routes.recognize_path request.path
    @app.call(env)
  end
end

如果我将问题行替换为

Rails.application.routes.recognize_path '/'

然后一切正常。

为什么将 request.path 作为参数发送给 recognize_path 会导致应用无法加载资产?

可以在此处找到该应用程序 https://github.com/mib32/wtf-middleware

Rails 资产管道在您可以在请求中看到的散列路径下编译资产,并且这些路径的处理方式与您的其他路由不同,因此 recognize_path 将无法正常运行。如果您不想让您的中间件弄乱资产,您应该跳过这些路径。

unless request.path =~ %r(^/assets/)
  Rails.application.routes.recognize_path request.path
end

或者,

begin
  Rails.application.routes.recognize_path request.path
rescue ActionController::RoutingError
  # pass
end