diff --git a/lib/middleware/builder.rb b/lib/middleware/builder.rb index d2a57ea..bfb54af 100644 --- a/lib/middleware/builder.rb +++ b/lib/middleware/builder.rb @@ -8,9 +8,9 @@ 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 @@ -18,10 +18,15 @@ module Middleware # 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 @@ -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 diff --git a/spec/middleware/builder_spec.rb b/spec/middleware/builder_spec.rb index c45ed3e..d43dcb4 100644 --- a/spec/middleware/builder_spec.rb +++ b/spec/middleware/builder_spec.rb @@ -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 = {}