App-wide Rack middleware and lib/

I’d like to get rid of trailing slashes by redirecting with a simple Rack middleware. The guides describe a similar example to add support for a JSON body parser.

In this example, the middleware goes into lib/foo_parser.rb and is then added via config in config/app.rb. That doesn’t work because the lib/foo_parser.rb is not required anywhere and won’t autoload since it’s not inside lib/MYAPP/. Moving it there won’t do the trick neither because that early in the boot process, the classes in lib/MYAPP/ are not yet available.

The obvious solution: Explicitly require the lib/foo_parser.rb.

Just to be sure: Is this a glitch in the guides and you should in fact require the middleware like that or do you have a better solution in mind which relies on Zeitwerk?

Rack middleware needs to be set up pretty earlier in the lifecycle of the app, so for that reason I never rely on autoloading for them.

The example in that guide page is using symbolic resolution, which is reserved for middleware namespaced within Hanami::Middleware, but ultimately it calls require.

@alassek Okay, built-in middleware added as a Symbol does an implicit require. However, scroll to the FooParser example at the very bottom of the guide: FooParser.new won’t fly unless you explicitly require "foo_parser" beforehand.

Any constant referenced in the App class is by definition required, because it is loaded before autoloading is instantiated.

Do you think it’s worth mentioning this in the guide?

1 Like

This should probably be explained in the Autoloading section. It can be tricky when you’re getting started. I don’t see this as directly applicable to middleware in particular though.

1 Like

In other words: Examples in the guides don’t include require to reduce bloat?

If so, good to know. Can be a little confusing though when not reading the guides top down.

@alassek Here’s a PR on autoloading in the config dir. What do you think, does something like this make sense?

I think that looks good, thanks for the PR!