12/08/2010

Rack Concept

Rack提供Ruby世界中Web Servers與Web Frameworks之間的橋樑。重要位置如同J2EE中Servlet,所有Java Web Application都透過相同介面與底層溝通。

如同Christian Neukirchen所言:

I noticed that there is a lot of code duplication among frameworks since they essentially all do the same things. And still, every Ruby web framework developer is writing his own handlers for every webserver he wants to use ...
However, in essence, dealing with HTTP is rather easy. In the end , you get a request and return a response.

因此Rack就被創造出來了 ! 也解救了大家,雖然在Java World是不可能看到這種事情發生 Orz。

從架構角度來思考Rack所佔位置:

From: Rack in Rails 3  Presentation

Rack官方定義:

Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.

那麼怎麼樣才是一個Rack程式所需要符合條件? Rack SPEC說到:

A Rack application is an Ruby object (not a class) that responds to call. It takes exactly one argument, the environment and returns an Array of exactly three values: status, the headers, and the body.

因此,只要有call function並且接收一個environment參數,且回傳一個Array由Http Status、Http Headers、Http Body所組成成員。

根據此需求撰寫一個最簡易Rack應用程式且透過Rack::Handler跑你喜歡Web Server!

[code lang="ruby"] ?> rack_app = lambda {|env| [200, {}, ["hello rack"]]} # >> Rack::Handler::WEBrick.run rack_app [2010-12-08 00:25:55] INFO WEBrick 1.3.1 [2010-12-08 00:25:55] INFO ruby 1.9.2 (2010-08-18) [x86_64-darwin10.5.0] [2010-12-08 00:25:55] INFO WEBrick::HTTPServer#start: pid=3996 port=3000 [/code]

Rack 趨勢所造成結果,統一中間層、介面,才有學習使用價值。

參考

f

No comments:

Post a Comment