Best place for Middlewares on Rails 6

646 Views Asked by At

I'm currently on Rais 6 and using middlewares. I've something working but I don't like it. How should I improve it?

Currently my middlewares are here:

app/middleware/my_middleware.rb

And on config/application.rb I'm calling

require_relative '../app/middleware/my_middleware

Without require_relative it's not working. If I add them on app folder it's not working either. What am I missing?

1

There are 1 best solutions below

6
On BEST ANSWER

Middleware cannot be reloaded because the middleware stack is setup during application boot and never rebuilt.

Because of that, you should tell the main autoloader to ignore the directory:

# config/initializers/zeitwerk.rb
Rails.autoloaders.main.ignore(Rails.root.join("app/middleware"))

and load the file yourself with require or require_relative just like you are doing.

There is some documentation about this use case here.