Question

What's the difference between the use and run methods in rackup files? It seems run is always at the end of config.ru, but it seems as if you should just be able to use use. Enlightening resources would also be very much appreciated.

Was it helpful?

Solution

use is for middlewares

class MyCustomMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    if condition
     env['set-header'] = 'Middleware Can modify the response & pass it into next middleware'
    end
    @app.call(env)
end

run takes an argument that responds to call and returns a final Rack response with a HTTP Response code like 200.

class MyApp
  def self.call(env)
   [200, { "Content-Type" => "text/html" }, ["OK"]]
 end
end

To understand the difference between use & run. lets see structure of typically rack app.

Typical Rack App Rack app includes multiple middleware(s) which respond to call but do not return final rack response & an Object that responds to call which returns final rack response which includes HTTP response code(200,404, 500 etc). so typically there will be multiple objects which act as middlewares & then a object which returns final rack response with response code.

Difference between use & run

Now with this, it seems can we can invoke use multiple times, once for each middleware & run only once in a single Rack App. so use will only invoke a middleware, while run will run the rack object which will return final rack response with HTTP status code.

example config.ru

use MyCustomMiddleware
use MyCustomMiddleware2
use MyCustomMiddleware3
run MyApp

In case if anything above is wrong, Let me know. So I can correct it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top