Recently I happened to see this word in Ruby code, use
, when I was going through some code related to goliath, middleware etc. Looks like it is different from include
/extend
, and require
.
Can somebody explain why this use
keyword exists, and how it is different from include
/require
? How does it work, when to use it?
The Documentation
As people have pointed out,
use
is not a Ruby keyword, it is in fact a method of theRack::Builder
class:This documentation (pointed out by @user166390) describes it like this:
The Source Code
I'm not too familiar with the
Rack::Builder
source code, but it looks like each time you calluse
with a new middleware module, it gets added to an array, and each module is run/injected in the reverse order in which it was added (last-in-first-out order, a.k.a. stack order). The result of running the previous middleware is passed to the next middleware in the stack viainject
:Lines 53-56:
Lines 81-87:
Lines 131-135:
Additional resources