Skip to content

Instantly share code, notes, and snippets.

@sfaxon
Created April 27, 2012 18:15
Show Gist options
  • Save sfaxon/2511491 to your computer and use it in GitHub Desktop.
Save sfaxon/2511491 to your computer and use it in GitHub Desktop.
builder
require 'debugger'
class Builder
def initialize(&block)
@wares = []
@runner = nil
instance_eval(&block) if block_given?
end
def use(middleware, *args, &block)
@wares << if block_given?
lambda { |app| middleware.new(app, *args, &block) }
else
lambda { |app| middleware.new(app, *args) }
end
end
def run(runner, *args, &block)
# runner is the entry point, you can think of it as the
# first middleware to run.
@runner = lambda { |env|
env = "I set a runner to #{runner}"
# env[:response] = Response.new
env
}
@runner
end
def to_app
# want to use @runner here rather than @wares.last?
# @wares << @runner
# @wares[0...-1].reverse.inject(@wares.last) { |a,e| e.call(a) }
@wares.inject(@runner) { |a,e| e.call(a) }
end
def call(env)
to_app.call(env)
end
end
class FirstMiddleware
def initialize(app = nil, args, &block)
@app = app
@args = args
puts "init: FirstMiddleware.new(#{app}, #{args})"
end
def call(env)
resp = @app.call(env)
puts "FirstMiddleware call env: #{env}, #{@args}"
resp += ", #{@args}"
resp
end
def inspect() "FirstMiddleware - 1" end
end
class SecondMiddleware
def initialize(app = nil, args, &block)
@app = app
@args = args
@block = instance_eval(&block) if block_given?
puts "init: SecondMiddleware.new(#{app}, #{args})"
end
def call(env)
resp = @app.call(env)
puts "SecondMiddleware call env: #{env}, #{@args}"
resp.upcase! # += ", #{@args}"
resp
end
def current_user=(x)
@current_user = x
end
def inspect() "SecondMiddleware - 1" end
end
class Runner
def initialize(app = nil)
puts "RUNNER INIT HAS: #{app}"
app
end
#
# def call(env)
# puts "RUNNER HAS: #{env}"
# @app.call(env)
# end
end
app = Builder.new {
use FirstMiddleware, 'first_arg'
use( SecondMiddleware, 'second_arg') { |t|
t.current_user= "aoeu"
}
run Runner
}
puts "result: #{app.call('start')}"
puts "app.inspect: #{app.inspect}"
a = 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment