19

Previously I had my middleware under lib/middleware/my_middle_ware.rb

However when doing this,

config.middleware.use MyMiddleWare

I receive a

NameError: uninitialized constant

Where is rails looking for the middleware?

Siva
  • 1,256
  • 3
  • 13
  • 29

5 Answers5

11

Look like rails wasn't looking for it.

I had to do the following for it to work.

Dir["./lib/middleware/*.rb"].each do |file|
  require file
end
Siva
  • 1,256
  • 3
  • 13
  • 29
  • 3
    This is the fix I went with also, but it seems like the framework should be loading these. Maybe it is a bug? – Jay Prall Dec 08 '17 at 18:21
  • @JayP. I agree. Is this a bug? I'm on Rails 5.2 and this is happening. Surprised there's not a standard auto-loaded directory for `middleware`, like there is for `models`, `controllers`, `views`, `mailers`, etc. – Joshua Pinter Nov 02 '20 at 00:44
  • 1
    For the record, I dug deep into this and here's the relevant discussion with the Rails Core members about where middleware should go and how to require it: https://github.com/rails/rails/issues/25525#issuecomment-479941866. In short, _"middleware can't be in app because they can't be reloaded. They should be in lib and if you put them in lib, require_relative will work."_ – Joshua Pinter Nov 02 '20 at 03:10
5

Create a folder app/middlewares and create your middleware file in this folder.

But unfortunately The app/middlewares folder is not loading even if I added to the load paths in Rails v5.2.2

config.autoload_paths << "#{Rails.root}/app/middlewares"
config.eager_load_paths << "#{Rails.root}/app/middlewares"

So you can use require explicitly as follows, add this line in application.rb

require_relative '../app/middlewares/my_middleware'

and load middleware:

config.middleware.use MyMiddleware

and call rake middleware to see the middleware stack.

Abhi
  • 3,361
  • 2
  • 33
  • 38
1

I believe you want to add your middleware to either your config/application.rb or your config/environments file.

config.middleware.use MyMiddleWare

This should work and append MyMiddleWare to the bottom of the middleware stack.

treiff
  • 1,246
  • 14
  • 24
1

Even before app/middleware contents are loaded if 'config.middleware.use' is called, I think you get the 'uninitialized Constant error'. The below should fix

config.middleware.use "MyMiddleWare"

If the above doesn't work, one of the below might be a no.

Is MyMiddleWare in app/middleware/my_middle_ware.rb ?

Is MyMiddleWare in lib/my_middle_ware.rb ?
ugandharc18
  • 651
  • 5
  • 7
  • 5
    I believe specifying your middleware class using a String was valid only before Rails 5. https://github.com/rails/rails/issues/25525 – turboladen Feb 20 '19 at 06:48
0

replacing middleware as a string in config/application.rb to config/environment/{environment} as a constant fixed the issue for me

Roel4811
  • 431
  • 4
  • 4