« Back to Index

Rack Server Example

View original Gist on GitHub

1. Simplest Rack server.rb

run lambda { |env| [200, {"Content-Type"=>"text/html"}, ["Hello World"]] }

2. Second Simplest Rack server.rb

@root = File.expand_path(File.dirname(__FILE__))

run lambda { |env|
  path = Rack::Utils.unescape(env['PATH_INFO'])
  index_file = @root + "#{path}index.html"
  [200, { 'Content-Type' => 'text/html' }, [File.exists?(index_file) ? File.read(index_file) : 'Hello World']]
}

# run with: rackup config.ru

3. Class based Rack server - app - app.rb

$: << File.dirname(__FILE__)

module TestComponent
  class Application
    def initialize
      puts "Application initialized"
    end

    # Rack requires object being run to have a `call` method which returns
    # an Array that includes the status code, http headers and a content response
    def call(env)
      [200, { 'Content-Type' => 'text/html' }, ['Hello World!']]
    end
  end
end

4. Class based Rack server - config.ru

$: << File.dirname(__FILE__)

require 'app/app'

run TestComponent::Application.new