[讀書心得] Growing Rails 筆記
讀 Growing Rails 的筆記
User interactions without a database
models 不一定要是 database table,有些 UI 不會更改到 table 值 例如: 登入表單、搜尋表單、輸入信用卡的表單、Validations and form roundtrips、Attribute setters 將字串改為數字.日期等、Language translations for model and attribute names、Transactional-style form submissions,所有驗證只能觸發一個動作通過
SignIn model 繼承 Plain model
sign_in instance 與 ActiveRecord object 有同樣的生命週期
Form Object
使用時機: 屬於 Model 的 Form 又需要 validation, callbacks 功能、需要在一個表單中更新多個 ActiveRecord model
Form Object with active_type:
Let your form inherit from ApplicationForm
Put your forms in app/forms/
檔案以 form 結尾並描述功能。例如:app/forms/admins/change_password_form.rb
initialize always requires a model that the form represents.
sync writes form data back to the model and nested models. This will only use setter methods on the model(s).
Extracting service objects
Service Object: 有某些類似的特定功能,像是一個『 service 』,跟資料庫中的 model 並無直接關係,因此拉出來獨立成為一個 class,增加程式碼的可讀性與維護性
使用時機: 1. method 邏輯極其複雜的時候 2. 跨 Model 使用,無法特別歸類於特定 Model 3. 與外部服務有較多關連 - 並非重要功能 4. 同一種 method 有許多類似的使用方法
參考:http://noelsaga.herokuapp.com/blog/2016/07/01/service-object-she-ji-jian-yi
Taming stylesheets
css 整理方法: BEM (short for Block, Element, Modifier)
好處:
最小化cascade 的影響 可以自由修改block,不用怕改東壞西 style 的再利用
Block:
例如: • A navigation bar • A blog article • A row of buttons • Columns that divide the available horizontal space
Element:
element 是 block 的子項目 例如: • The block “navigation bar” comprises multiple “section” elements • The block “blog article” comprises an element “title” and an element “text” • The block “columns” contains multiple “column” elements.
Modifiers:
如果需要一個像其他 block 90% 的新block 例如: • A smaller version of an article • A differently colored button for a form’s primary action • Highlighting the current navigation section
將 modifiers 當作 classes (blocks) 與 methods (elements) 的可選參數
modifiers 不帶有 block 的名稱,使用有修飾性的名稱命名
例如: is_small
or has_children
BEM anti-patterns
- Badly named elements (discouraging reuse)
- Giant “god” blocks that are many pages long (making reuse impossible)
- Blocksthatdescribeindividualscreens(insteadofattemptingtoextractreusablecomponents)
- Violations of the BEM prime directive (making the whole exercise pointless)