Skip to content
This repository was archived by the owner on Oct 31, 2023. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions lib/middleware/builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,25 @@ module Middleware
#
# Building a middleware stack is very easy:
#
# app = Middleware::Builder.new do
# use A
# use B
# app = Middleware::Builder.new do |b|
# b.use A
# b.use B
# end
#
# # Call the middleware
# app.call(7)
#
class Builder
# Initializes the builder. An optional block can be passed which
# will be evaluated in the context of the instance.
# will either yield the builder or be evaluated in the context of the instance.
#
# Example:
#
# Builder.new do |b|
# b.use A
# b.use B
# end
#
# Builder.new do
# use A
# use B
Expand All @@ -35,7 +40,14 @@ class Builder
def initialize(opts=nil, &block)
opts ||= {}
@runner_class = opts[:runner_class] || Runner
instance_eval(&block) if block_given?

if block_given?
if block.arity == 1
yield self
else
instance_eval(&block)
end
end
end

# Returns a mergeable version of the builder. If `use` is called with
Expand Down
32 changes: 32 additions & 0 deletions spec/middleware/builder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,38 @@ def appender_proc(data)
Proc.new { |env| env[:data] << data }
end

context "initialized with a block" do
context "without explicit receiver" do
it "instance evals the block" do
data = {}
proc = Proc.new { |env| env[:data] = true }

app = described_class.new do
use proc
end

app.call(data)

data[:data].should == true
end
end

context "with explicit receiver" do
it "yields self to the block" do
data = {}
proc = Proc.new { |env| env[:data] = true }

app = described_class.new do |b|
b.use proc
end

app.call(data)

data[:data].should == true
end
end
end

context "basic `use`" do
it "should add items to the stack and make them callable" do
data = {}
Expand Down