Created
January 14, 2009 17:32
-
-
Save lifo/46974 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Rack | |
class Callbacks | |
def initialize(&block) | |
@before = [] | |
@after = [] | |
instance_eval(&block) if block_given? | |
end | |
def before(middleware, *args, &block) | |
if block_given? | |
@before << middleware.new(*args, &block) | |
else | |
@before << middleware.new(*args) | |
end | |
end | |
def after(middleware, *args, &block) | |
if block_given? | |
@after << middleware.new(*args, &block) | |
else | |
@after << middleware.new(*args) | |
end | |
end | |
def run(app) | |
@app = app | |
end | |
def call(env) | |
@before.each {|c| c.call(env) } | |
response = @app.call(env) | |
@after.each {|c| c.call(env) } | |
response | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rack/mock' | |
require 'rack/contrib/callbacks' | |
class Flame | |
def call(env) | |
env['flame'] = 'F Lifo..' | |
end | |
end | |
class Pacify | |
def initialize(with) | |
@with = with | |
end | |
def call(env) | |
env['peace'] = @with | |
end | |
end | |
class Finale | |
def call(env) | |
$hax_logger = 'lol' | |
end | |
end | |
context "Rack::Callbacks" do | |
specify "works for love and small stack trace" do | |
callback_app = Rack::Callbacks.new do | |
before Flame | |
before Pacify, "with love" | |
run lambda {|env| [200, {}, env['flame'] + env['peace']] } | |
after Finale | |
end | |
app = Rack::Builder.new do | |
run callback_app | |
end.to_app | |
response = Rack::MockRequest.new(app).get("/") | |
response.body.to_s.should.equal 'F Lifo..with love' | |
$hax_logger.should.equal 'lol' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment