Module: Otto::Core::MiddlewareManagement

Included in:
Otto
Defined in:
lib/otto/core/middleware_management.rb

Overview

Middleware management module for building and configuring the Rack middleware stack. Provides the public API for adding middleware and building the application.

Instance Method Summary collapse

Instance Method Details

#build_app!Object

Builds the middleware application chain Called once at initialization and whenever middleware stack changes

IMPORTANT: If you have routes with auth requirements, you MUST add session middleware to your middleware stack BEFORE Otto processes requests.

Session middleware is required for RouteAuthWrapper to correctly persist session changes during authentication. Common options include:

  • Rack::Session::Cookie (requires rack-session gem)

  • Rack::Session::Pool

  • Rack::Session::Memcache

  • Any Rack-compatible session middleware

Example:

use Rack::Session::Cookie, secret: ENV['SESSION_SECRET']
otto = Otto.new('routes.txt')


27
28
29
30
# File 'lib/otto/core/middleware_management.rb', line 27

def build_app!
  base_app = method(:handle_request)
  @app = @middleware.wrap(base_app, @security_config)
end

#middleware_enabled?(middleware_class) ⇒ Boolean

Check if a specific middleware is enabled

Parameters:

  • middleware_class (Class)

    Middleware class to check

Returns:

  • (Boolean)

    true if middleware is in the stack



65
66
67
# File 'lib/otto/core/middleware_management.rb', line 65

def middleware_enabled?(middleware_class)
  @middleware.includes?(middleware_class)
end

#middleware_stackArray

Compatibility method for existing tests

Returns:

  • (Array)

    List of middleware classes



49
50
51
# File 'lib/otto/core/middleware_management.rb', line 49

def middleware_stack
  @middleware.middleware_list
end

#middleware_stack=(stack) ⇒ Object

Compatibility method for existing tests

Parameters:

  • stack (Array)

    Array of middleware classes



55
56
57
58
59
# File 'lib/otto/core/middleware_management.rb', line 55

def middleware_stack=(stack)
  @middleware.clear!
  Array(stack).each { |middleware| @middleware.add(middleware) }
  build_app! if @app # Rebuild app if already initialized
end

#use(middleware) ⇒ Object

Add middleware to the stack

Parameters:

  • middleware (Class)

    Middleware class to add

  • args

    Additional arguments passed to middleware constructor



36
37
38
39
40
41
42
43
44
45
# File 'lib/otto/core/middleware_management.rb', line 36

def use(middleware, ...)
  ensure_not_frozen!
  @middleware.add(middleware, ...)

  # NOTE: If build_app! is triggered during a request (via use() or
  # middleware_stack=), the @app instance variable could be swapped
  # mid-request in a multi-threaded environment.

  build_app! if @app # Rebuild app if already initialized
end