Class: Protocol::HTTP::Middleware::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/protocol/http/middleware/builder.rb

Overview

A convenient interface for constructing middleware stacks.

Constant Summary collapse

TOPLEVEL_BINDING =
->(builder){builder.instance_eval{binding}}

Instance Method Summary collapse

Constructor Details

#initialize(default_app = NotFound) ⇒ Builder

Initialize the builder with the given default application.



16
17
18
19
# File 'lib/protocol/http/middleware/builder.rb', line 16

def initialize(default_app = NotFound)
	@use = []
	@app = default_app
end

Instance Method Details

#build(&block) ⇒ Object

Build the middleware application using the given block.



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/protocol/http/middleware/builder.rb', line 25

def build(&block)
	if block_given?
		if block.arity == 0
			instance_exec(&block)
		else
			yield self
		end
	end
	
	return self
end

#run(app) ⇒ Object

Specify the (default) middleware application to use.



50
51
52
# File 'lib/protocol/http/middleware/builder.rb', line 50

def run(app)
	@app = app
end

#to_appObject

Convert the builder to an application by chaining the middleware together.



57
58
59
# File 'lib/protocol/http/middleware/builder.rb', line 57

def to_app
	@use.reverse.inject(@app){|app, use| use.call(app)}
end

#use(middleware, *arguments, **options, &block) ⇒ Object

Use the given middleware with the given arguments and options.



43
44
45
# File 'lib/protocol/http/middleware/builder.rb', line 43

def use(middleware, *arguments, **options, &block)
	@use << proc{|app| middleware.new(app, *arguments, **options, &block)}
end