简体   繁体   中英

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

The next middleware causes Rails app to fail loading assets

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

if i replace the problem line with

Rails.application.routes.recognize_path '/'

then everything works again.

How come that sending request.path as the argument to the recognize_path can cause app to be unable to load assets?

The app can be found here https://github.com/mib32/wtf-middleware

The Rails asset pipeline compiles assets under the hashed paths you can see in the request, and those are handled differently than your other routing, so recognize_path won't behave properly. If you don't need your middleware to be messing with assets, you should skip these paths.

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

Or,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM