Skip to content

Instantly share code, notes, and snippets.

@tuzz
Created May 5, 2012 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuzz/2604631 to your computer and use it in GitHub Desktop.
Save tuzz/2604631 to your computer and use it in GitHub Desktop.
Playing with rack
class Rack::Reverse
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
[status, headers, [body.join.reverse]]
end
end
class Rack::Timer
def initialize(app)
@app = app
end
def call(env)
before = Time.now
status, headers, body = @app.call(env)
after = Time.now
prefix = "Response time: #{after - before}\n\n"
[status, headers, [prefix] + body]
end
end
class Rack::Delay
def initialize(app, delay)
@app = app
@delay = delay
end
def call(env)
sleep(@delay)
@app.call(env)
end
end
class Hola
def status
200
end
def headers
{ 'Content-Type' => 'text/plain' }
end
def body
body = 'Hello, world!'
body = 'Bonjour tout le monde!' if ['fr', 'fr-fr', 'french'].include?(language)
body = 'Hallo, Welt!' if ['de', 'de-de', 'german'].include?(language)
[body]
end
def call(env)
@env = env
[status, headers, body]
end
def self.call(env)
new.call(env)
end
protected
def language
@language ||= Rack::Request.new(@env).query_string.downcase
end
end
use Rack::Timer
map '/' do
use Rack::Reverse
use Rack::Delay, 1.5
run Hola
end
map '/author' do
run Proc.new { |env| [200, { 'Content-Type' => 'text/plain'}, ['Christopher Patuzzo']] }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment