Ruby Web Framework : 觀察與概念


緣起

前前後後寫 Ruby 也寫了一陣子,用習慣了別人寫的套件、別人寫的 framework 以後,慢慢的也對於各種套件撰寫的原理有了些好奇,開始想要自己編寫一些屬於自己的套件和 framework 來了解一些背後的原理與方法,從過年前到最近,花了一點時間來自己摸索怎麼用 Ruby 來寫一個 web framework ,在過程中學到了許多東西,慢慢的從很多方向來思考 framework 需要什麼。 在這篇裡面我會先將各個模組說明,之後會一個一個來討論。

觀察

從以前就不喜歡看一堆的 document 來學東西,我喜歡從自己的發現中學習,高見龍前輩曾經在日本 RubyKaigi 上發表「Code Reading, Learning More about Ruby by Reading Ruby Source Code」,因此我開始觀察不同的 web framework 試試看能不能有什麼發現。

Web Framework 都有一個 config.ru 檔案?
這是要做什麼的?

首先呢,先查了一些資料,意外的發現網路上沒有太多關於 config.ru 單獨的說明,但是可以大致上了解, config.ru 是一個 Rack 的設定檔與執行檔,那什麼是 Rack 呢?

Rack is a nice Ruby-fied replacement for CGI.
Rack sits between all the frameworks (Rails, Sinatra, Rulers) and all the app servers (thin, unicorn, Rainbows, mongrel) as an adapter.
Rack is a convenient way to build your Ruby app out of a bunch of thin layers, like a stack of pancakes. The layers are called middleware. Or pancakes, why not?

What Is Rack? : a Primer

簡單的說,Rack 就是一個用 Ruby 做的 CGI ,它在應用程式和伺服器之間做資料的轉換和處理,可以讓我們用更邏輯的方式來撰寫程式,對於 Ruby framework 的抽象化有很大的幫助,而 config.ru 就是 Rack 的執行點,也可以稱為設定檔,而 config.ru 是用純 Ruby 的語法所寫成,理論上,我們可以把 framework 的所有的東西都寫在 config.ru 裡面,就能執行了。但是,我們不要,也不應該這麼做,對於 Ruby 的程式撰寫,其中最重要的一個目的在於「語意化」,用以提升程式可再利用性可維護性提升開發速度,為了維持語意化的目的,使用多檔案的架構勢必是不可少的,那,如何區分資料夾呢?

每個 MVC 架構的程式對資料夾的分配好像都很類似

以前寫過的各種 MVC 框架的結構感覺上都大同小異,將 Modal , Controller , View 分開來放,將設定檔放在 config 資料夾內,可以讓設定檔和程式的邏輯分開,將 Modal , Controller , View 分開,可以在設計上更加方便,至於什麼是 MVC 架構呢?

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces on computers. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.

  • The model directly manages the data, logic and rules of the application.
  • A view can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.
  • The third part, the controller, accepts input and converts it to commands for the model or view.
    Wikipedia - Modal View Controller

大部分的 framework 都有如以下的結構:


tree structure

Public 可以放什麼東西呢?

在 Public 資料夾中,一般是放靜態檔案的地方,系統裡的靜態檔案一般可以分成以下的幾種:

  • asset ( css / JavaScript )
  • image
  • other format file ( .pdf / .docs / *.xlsx … )

在 Rack server 的機制裡面,這個資料夾的內容可以直接被下載,用以增加頁面加載的速度,不用透過自身 server 的重新 render ( 像是 nodejs 的 pm2 的作法 ) 這樣對於有大量靜態資源的頁面來說,是個較容易省下計算資源和增加連線效率的方法。

Rakefile 是做什麼的呢?

Rake 是一個 Ruby 中的任務自訂小工具,我們可以透過在 Rakefile 裡面自己撰寫一些任務,來幫忙我們加速開發與上線的麻煩點,Rakefile 裡面使用到的都是標準的 Ruby 語法,也就是說,我們可以用簡單的幾行 Ruby 就可以進行一些專案上的控制,如:DB migration, install project …我們之後會討論如何撰寫 Rakefile 的任務。

簡單總結

  • config.ru 是一個 Rack-based 的 framework 主程式
  • MVC 框架的基本資料夾格式為:
    • app/
      • modal/
      • view/
      • controller/
    • public/
  • Public 是靜態檔案的集散地
  • Rakefile 定義了這個程式或 framework 所使用到的一些指令行任務