Rhythm & Biology

Engineering, Science, et al.

rack事始め

rackのインストール

% gem install rack

まずはHello World

# filename: hello.ru
require 'rubygems'
require 'rack'

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

run Hello.new

実行

% rackup hello.ru
[2011-06-05 02:51:18] INFO  WEBrick 1.3.1
[2011-06-05 02:51:18] INFO  ruby 1.9.2 (2011-02-18) [x86_64-darwin10.7.0]
[2011-06-05 02:51:18] INFO  WEBrick::HTTPServer#start: pid=88207 port=9292

ブラウザでlocalhost:9292にアクセスすると、Hello Worldが表示されます。サーバはCtrl-Cで終了できます。

これだけでは退屈なので、Rack::RequestとRack::Responseを使って色々な情報を出力してみます。

require 'rubygems'
require 'rack/request'
require 'rack/response'

class Hello
  def call(env)
    req = Rack::Request.new(env)
    params = req.params

    body = "Method: #{req.request_method}\n"
    body += "URL: #{req.url}\n"
    body += "Scheme: #{req.scheme}\n"                                           
    body += "Host: #{req.host}\n"
    body += "Port: #{req.port}\n"
    body += "Fullpath: #{req.fullpath}\n"
    body += "Pathinfo: #{req.path_info}\n"
    body += "Referrer: #{req.referrer}\n"
    body += "Scriptname: #{req.script_name}\n"

    params.each {|key, value|
      body += "#{key} => #{value}\n"
    }   

    res = Rack::Response.new
    res.status = 200 
    res["Content-Type"] = "text/plain"
    res.write body
    res.finish
  end 
end

run Hello.new