Skip to content

Instantly share code, notes, and snippets.

@radavis
Last active February 2, 2023 16:13
Show Gist options
  • Save radavis/be012e387ba93ace94f0992bb784466a to your computer and use it in GitHub Desktop.
Save radavis/be012e387ba93ace94f0992bb784466a to your computer and use it in GitHub Desktop.

Middleware

  • HTTP Request/Response Cycle
  • MVC

How does the application know how to map HTTP requests to Controller actions?

Rack::Middleware

Rails routes are a middleware that map the HTTP Verb and Path (within a HTTP request) to a Controller action.

Wobbe::Application.routes.draw do
  get '/profile', to: 'users#show'  # UsersController.action(:show).call
end

Middleware in Use

A chain of classes that are initialized with a Rack Application, and respond to #call with [status_code, headers, body].

$ rake middleware
use Rails::Rack::Logger  # responsible for the files in ./log/
use Rollbar::Middleware::Rails::RollbarMiddleware  # responsible for reporting 400/500 status codes.
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash
...
run Wobbe::Application.routes  # the HTTP Verbs and Paths that Wobbe can respond to

Rails Middleware

Types of Middleware

  • Development/Debugging
  • Logging/Error reporting
  • Session management
  • Routing

Two common types: When given a HTTP request, perform a side effect, or return some information (respond).

Examples

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

  def call(env)
    # before HTTP response
    status, headers, body = @app.call(env)  # call the next middleware application
    # after building HTTP response
    [status, headers, body]
  end
end

Questions:

  • What is stored in env?
  • Where is @app.call(env) located in the middleware?
  • What happens in the #call method?
  • What does the #call method return?
  • What could we do with this?

Other Reading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment