Essentail Rails Design Pattern

Write Good Rails Code

Scope

Scope 的最前身,是一套 Rails Plugin:has_finder。在遙遠的 2007 年,那時候的 ActiveRecord 遠不如現今強大。很多 finder 都需要自己定義 method 手刻。

如果今天需要下一段 query 做出 recent 效果,我們會手寫一段 method

1
2
3
def recent
   find(:all, :order => created_at DESC)
end

需要 popular

1
2
3
def popular
   find(:all, :order => “visitors_count DESC”)
end

但如果,我們需要 Post.recent.popular 呢?

Rails 的 method 好像不能這樣串。 腦袋當機….

也許我們可以寫個 recent_and_popular

但是,在別一段 code 我們需要的是 Post.popular.recent 呢?

兩個條件已經夠讓你頭大了,但真實世界會有無窮的條件等著排列組合。你不可能永遠定義 method 去暴力解決串接的問題。

has_finder 就是設計來滿足串接的需求,自動產生需要產生的 query。而 has_finder 在 Rails 2 時被納為內建 feature named_scope,在 Rails 3 時強化原先的 feature,再次更名為 scope。

Default Scope

#TODO

Other Scope

#TODO

Comments