ruk·si

🛤️ Ruby on Rails
Middlewares

Updated at 2016-04-08 00:07

Middleware stack is a list of Ruby classes which each request and response will pass before being being feed to your application. Middlewares usually provide features like authentication, authorization, caching, decoration, monitoring and execution.

bin/rake middleware
use Rack::Sendfile
use ActionDispatch::Static
use Rack::Lock
# ...
use Warden::Manager
run MyApp::Application.routes

From the above we can see that if you give Rack a path that resolves to a static file, it will be served directly from the web server without involving the Rails stack.

You can change middleware stack in

config.middleware.use(new_middleware, args) # Added as last.
config.middleware.insert_after(existing_middleware, new_middleware, args)
config.middleware.insert_before(existing_middleware, new_middleware, args)
config.middleware.swap(existing_middleware, new_middleware, args)
config.middleware.delete(middleware)

Example middleware:

# in config/application.rb
config.middleware.use 'FooBar'

# in config/initializers/foo_bar.rb
class FooBar
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, response = @app.call(env)
    [status, headers, response.body << "\nHi from #{self.class}"]
  end
end

Source