Better Rails Structure

by winson, 11 months ago.

剛開始接觸Rails時,看到他把系統目錄架構規劃的那麼簡單明瞭,跟那些又是XML,又是壓縮檔,又是com.very.long.pasta.is.spaghetti…沒完沒了的義大利麵架構比起來,真的很令人感動。

Rails裡頭各種app, model, controller, model等都規劃的清清楚楚,無論什麼樣的人來寫Rails的程式,各種檔案之間的關連是很容易讓人明白的。

例如:

app/
  controllers/    
    admin_controller.rb
    application.rb
    store_controller.rb
  helpers/
    admin_helper.rb
    application_helper.rb
    store_helper.rb
  models/
    cart.rb
    line_item.rb
    product.rb
  views/
    admin/
      _form.rhtml
      edit.rhtml
      list.rhtml
      new.rhtml
      show.rhtml
  layouts/
    admin.rhtml
    store.rhtml
    store/
      index.rhtml
      my_cart.rhtml
這是一個網路書店程式,各種元件劃分的相當清楚,但是好還可以更好。

常寫Rails程式就知道,改了model之後,也許需要改一下controller;改了controller之後,也許需要改一下view,這時,就需要在不同的目錄間穿梭來回。

原本按模組劃分的方式(以app, model, view等)是不錯,那改成元件劃分呢,例如application一包、store一包、admin也自己一包呢?

例如:

app/
  admin/
    admin_controller.rb
    admin_helper.rb
    admin_form.rhtml
    admin_layout.rhtml
    admin_edit.rhtml
    admin_list.rhtml
    admin_new.rhtml
    admin_show.rhtml
    admin_model.rb
    admin_migrations.rb
  application/    
    application.rb
    application_helper.rb
    application_layout.rhtml
  store/    
    store_controller.rb
    store_helper.rb
    store_index.rhtml
    store_my_cart.rhtml
    store_layout.rhtml
    store_model.rb
    store_migrations.rb
models/
  cart.rb
  line_item.rb
  product.rb
如此一來,屬於store的,不管是controller, model, view, helper, layout,甚至是model都在一起,不同模組的檔案用底線做區隔,目錄架構變得扁平化,而且也不會有太深、太多層的目錄。

這樣子改起程式來應該更加方便吧。

最後之所以要獨立一個model,是因為很多model不必然綁在一個controller上頭,也許跟controller一點關係也沒有。

不知道有沒有人提過這樣子的目錄架構想法呢?


  • Posted in Rails, on Wednesday, August 08, 2007, at 11:44 PM.