Skip to content

Instantly share code, notes, and snippets.

@lporras
Last active August 29, 2015 14:27
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 lporras/00a2caba1ba56083f5de to your computer and use it in GitHub Desktop.
Save lporras/00a2caba1ba56083f5de to your computer and use it in GitHub Desktop.
Rack Basics

Rack Basics

Objective

Understand Rack, an essential component of Rails.

Rack

Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. It includes basic implementations of request, response, cookies & sessions. And a good number of useful middlewares.

Bundler

Bundler is a package manager that sandboxes an application or library. Libraries are called gems.

Create a Gemfile that requires Rack and Mongrel, a web server.

source "http://rubygems.org"

gem "rack", "1.3.5"
gem "mongrel", "1.2.0.pre2"

Install bundler with RubyGem.

$ gem install bundler

Install gems.

$ bundle install
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

Server

A simple Rack server responds to a single HTTP request. The call method takes one parameter - an environment that contains information about the HTTP request. The response from the call method must be an array of three elements: an HTTP return code, headers and an array of body parts.

require 'rubygems'
require 'rack'

class HelloWorld
  def call(env)
    [200, {"Content-Type" => "text/html"}, ["Hello Rack!"]]
  end
end

Rack::Handler::Mongrel.run HelloWorld.new, :Port => 9292 # Remember the uppercase 'P'

It can be run with ruby.

$ ruby server.rb

Navigate to localhost:9292.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment