What problem does it solve?
Effectively extending and customizing Ruby web applications (like Sinatra or Rails) often involves working with Rack middleware. Understanding how to develop, configure, and order middleware is crucial for building robust and performant applications.
Core Features & Use Cases
- Middleware Structure: Learn the basic
initialize and call methods for creating custom Rack middleware, forming the foundation of your web stack.
- Custom Middleware Development: Step-by-step examples for building request logging, token authentication, caching, and request transformation middleware to extend functionality.
- Middleware Ordering Patterns: Guidance on structuring middleware stacks for security-first or API-focused applications, and using conditional middleware for flexible deployment.
- Use Case: A developer needs to add custom logging and authentication to their Sinatra application without modifying the core application logic. This Skill provides detailed examples for creating
RequestLogger and TokenAuthentication middleware, showing how to integrate them into the Rack stack and ensure proper ordering.
Quick Start
Basic Rack middleware structure
class MyMiddleware
def initialize(app, options = {})
@app = app
@options = options
end
def call(env)
# Before request
status, headers, body = @app.call(env)
# After request
[status, headers, body]
end
end
Usage in config.ru
use MyMiddleware, option: 'value'