module Roda::RodaPlugins::Middleware

  1. lib/roda/plugins/middleware.rb

The middleware plugin allows the Roda app to be used as rack middleware.

In the example below, requests to /mid will return Mid by the Mid middleware, and requests to /app will not be matched by the Mid middleware, so they will be forwarded to App.

class Mid < Roda
  plugin :middleware

  route do |r|
    r.is "mid" do
      "Mid"
    end
  end
end

class App < Roda
  use Mid

  route do |r|
    r.is "app" do
      "App"
    end
  end
end

run App

It is possible to use the Roda app as a regular app even when using the middleware plugin.

You can support configurable middleware by passing a block when loading the plugin:

class Mid < Roda
  plugin :middleware do |middleware, *args, &block|
    middleware.opts[:middleware_args] = args
    block.call(middleware)
  end

  route do |r|
    r.is "mid" do
      opts[:middleware_args].join(' ')
    end
  end
end

class App < Roda
  use Mid, :foo, :bar do |middleware|
    middleware.opts[:middleware_args] << :baz
  end
end

# Request to App for /mid returns
# "foo bar baz"

Note that when supporting configurable middleware via a block, the middleware used is a subclass of the class loading the plugin, instead of the class itself. This is done so the same class can be used as middleware with multiple separate configurations.

Methods

Public Class

  1. configure

Public Class methods

configure (app, opts={}, &block)

Configure the middleware plugin. Options:

:env_var

Set the environment variable to use to indicate to the roda application that the current request is a middleware request. You should only need to override this if you are using multiple roda middleware in the same application.

[show source]
# File lib/roda/plugins/middleware.rb, line 73
def self.configure(app, opts={}, &block)
  app.opts[:middleware_env_var] = opts[:env_var] if opts.has_key?(:env_var)
  app.opts[:middleware_env_var] ||= 'roda.forward_next'
  app.opts[:middleware_configure] = block if block
end