Rack is the gem that provides the interface between web frameworks (ruby on rails, sinatra) and web servers (webrick, puma, unicorn) in ruby world.

The Rack interface

Respond to call method, which accepts a single argument called env, and returns an array with three elements: status, headers, body.

The rack hello world - class version

require 'rack'

class HelloWorld
  def call(env)
    [200, {'Content-Type' => 'text/plain'}, ['Hello World']]
  end
end

Rack::Handler::WEBrick.run HelloWorld.new

# open http://localhost:8080
# Hello World

The rack hello world - lambda version

require 'rack'

app = -> (env) { [200, {'Content-Type' => 'text/plain'}, ['Hello World']] }

Rack::Handler::WEBrick.run app

# open http://localhost:8080
# Hello World

References

TOP▲
Post tagged with: ruby