Class: Roda::RodaPlugins::Middleware::Forwarder

Inherits:
Object
  • Object
show all
Defined in:
lib/roda/plugins/middleware.rb

Overview

Forwarder instances are what is actually used as middleware.

Instance Method Summary collapse

Constructor Details

#initialize(mid, app, *args, &block) ⇒ Forwarder

Make a subclass of mid to use as the current middleware, and store app as the next middleware to call.



92
93
94
95
96
97
98
99
100
# File 'lib/roda/plugins/middleware.rb', line 92

def initialize(mid, app, *args, &block)
  @mid = Class.new(mid)
  if configure = @mid.opts[:middleware_configure]
    configure.call(@mid, *args, &block)
  elsif block || !args.empty?
    raise RodaError, "cannot provide middleware args or block unless loading middleware plugin with a block"
  end
  @app = app
end

Instance Method Details

#call(env) ⇒ Object

When calling the middleware, first call the current middleware. If this returns a result, return that result directly. Otherwise, pass handling of the request to the next middleware.



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/roda/plugins/middleware.rb', line 105

def call(env)
  res = nil

  call_next = catch(:next) do
    env[@mid.opts[:middleware_env_var]] = true
    res = @mid.call(env)
    false
  end

  if call_next
    res = @app.call(env)

    if modified_headers = env.delete('roda.response_headers')
      res[1] = modified_headers.merge(res[1])
    end
  end

  if handle_result = @mid.opts[:middleware_handle_result]
    handle_result.call(env, res)
  end

  res
end