Rack

Rack 是什麼?

a Ruby Webserver Interface
Rack

Ruby 實作的網站伺服器介面。

規格

提供一個能夠回應 call 方法的物件,並且回傳一個包含以下三個元素的陣列:
1.HTTP 狀態(數字)
2.HTTP Header(Hash)
3.HTTP Body(陣列)

動起來!

$ mkdir rack_demo $ cd rack_demo $ rackup # ru = rackup configuration /Users/emily/Desktop/Ruby_Bootcamp/rack-demo/config.ru not found

config.ru 檔案

run Proc.new { [ 200, # 狀態 { "Content-Type" => "text/html" }, # HEAD ["Hello, rack"] # BODY ] }
$ rack-demo rackup Puma starting in single mode... * Puma version: 5.6.5 (ruby 3.2.0-p0) ("Birdie's Version") * Min threads: 0 * Max threads: 5 * Environment: development * PID: 49301 * Listening on http://127.0.0.1:9292 * Listening on http://[::1]:9292 Use Ctrl-C to stop

只要有支援 call 方法的物件就行了

class Cat def call(env) [ 200, { "Content-Type" => "text/html" }, ["helle test test"] ] end end kitty = Cat.new run kitty

中介軟體 Middleware

class Backdoor def initialize(app, whom = "no one") @app = app @whom = whom end def call(env) status, headers, body = @app.call(env) body << "<br />Powered by #{@whom}!" [status, headers, body] end end use Backdoor, "5xRuby" run Proc.new { [200, { "Content-Type" => "text/html" }, ["Hello, Rack"]] }

疊疊樂

use Backdoor, "Taipei" # 壓在最下面,但最後執行 use Backdoor, "Hello" use Backdoor, "Kitty" run Proc.new { [200, { "Content-Type" => "text/html" }, ["Hello, Rack"]] }

關於 Ruby on Rails

Ruby on Rails 其實也是一種 Rack 應用程式

# This file is used by Rack-based servers to start the application. require_relative 'config/environment' run Rails.application # 會有一個 run 進入點

Rails 也掛了一大串的 middleware

$ rails middleware use Webpacker::DevServerProxy use ActionDispatch::HostAuthorization use Rack::Sendfile use ActionDispatch::Static ...略... use Rack::Head use Rack::ConditionalGet use Rack::ETag use Rack::TempfileReaper run MyApp::Application.routes