Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active February 22, 2019 09:55
Show Gist options
  • Save Integralist/8341704 to your computer and use it in GitHub Desktop.
Save Integralist/8341704 to your computer and use it in GitHub Desktop.
Rack Server Example
run lambda { |env| [200, {"Content-Type"=>"text/html"}, ["Hello World"]] }
@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
$: << 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
$: << File.dirname(__FILE__)
require 'app/app'
run TestComponent::Application.new
@Integralist
Copy link
Author

class MyApp
  attr_reader :request

  def initialize(request)
    @request = request
  end

  def status
    if homepage?
      200
    else
      404
    end
  end

  def headers
    {'Content-Type' => 'text/html', 'Content-Length' => body.size.to_s}
  end

  def body
    content = if homepage?
      "Your IP: #{request.ip}"
    else
      "Page Not Found"
    end

    layout(content)
  end

  private

  def homepage?
    request.path_info == '/'
  end

  def layout(content)
%{<!DOCTYPE html>
<html lang="en">
  <head>

    <meta charset="utf-8">
    <title>Your IP</title>
  </head>
  <body>
    #{content}
  </body>
</html>}
  end
end

class MyApp::Rack
  def call(env)
    request = Rack::Request.new(env)
    my_app = MyApp.new(request)

    [my_app.status, my_app.headers, [my_app.body]]
  end
end

Run it with rackup and the following config.ru:

require "rack-server"
run MyApp::Rack.new

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