Rack is used for practically every framework that runs on Ruby yet many Rails developers don't really understand what it is or how it works. Understanding rack can make these frameworks feel less daunting. It's surprisingly easy to understand when you take a look at it.
# hello_world.rb
require 'rack'
class HelloWorld
def call(env)
[200, {"Content-Type" => "text/plain"}, ["Hello, World!"]]
end
end
Rack::Handler::WEBrick.run HelloWorld.new
ruby hello_world.rb
require 'thin'
class HelloWorld
def call(env)
[200, {"Content-Type" => "text/plain"}, ["Hello, World!\n"]]
end
end
class GoodbyeWorld
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
body << "Goodbye, World!\n"
[status, headers, body]
end
end
use GoodbyeWorld
run HelloWorld.new
require 'thin'
class HelloWorld
def call(env)
[200, {"Content-Type" => "text/plain"}, ["Hello, World!\n"]]
end
end
class GoodbyeWorld
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
body << "Goodbye, World!\n"
[status, headers, body]
end
end
class Benchmarker
def initialize(app)
@app = app
end
def call(env)
start_time = current_time
status, headers, body = @app.call(env)
end_time = current_time
body << "Took #{end_time - start_time} seconds to complete"
[status, headers, body]
end
def current_time
Time.now.to_f * 1000
end
end
use Benchmarker
use GoodbyeWorld
run HelloWorld.new
require 'thin'
class HelloWorld
def call(env)
if env['flip'] == 'heads'
[200, {"Content-Type" => "text/plain"}, ["Hello, World!\n"]]
else
[401, {"Content-Type" => "text/plain"}, ["Naughty naughty\n"]]
end
end
end
class CoinFlip
def initialize(app)
@app = app
end
def call(env)
env['flip'] = %w[heads tails].sample
@app.call(env)
end
end
use CoinFlip
run HelloWorld.new
require 'thin'
class HelloWorld
def call(env)
[200, {"Content-Type" => "text/plain"}, ["Hello, World!\n"]]
end
end
class CoinFlip
def initialize(app)
@app = app
end
def call(env)
if %w[heads tails].sample == 'heads'
@app.call(env)
else
[200, {"Content-Type" => "text/plain"}, ["Winner winner chicken dinner!\n"]]
end
end
end
class GoodbyeWorld
def initialize(app)
@app = app
end
def call(env)
status, headers, body = @app.call(env)
body << "Goodbye, World!\n"
[status, headers, body]
end
end
use CoinFlip
use GoodbyeWorld
run HelloWorld.new
From us to your inbox weekly.