以下の記事は、調査の結果現状のRuby on Rails
では期待通りに動かないことがわかりました。
Rails-2.1の新機能であるnamed_scopeを使うと、従来のwith_scope
では綺麗にかけなかったスコープの選択を簡潔に記述することができます。
1 def gadgets_on_sidebar(place = 'index')
2 case place.to_s
3 when 'index'; Gadget.on_index
4 when 'show'; Gadget.on_show
5 else Gadget.all
6 end.with_scope{active_gadgets + Gadget.mandatories}
7 end
各スコープメソッドは、ActiveRecord::NamedScope::Scope
オブジェクトを返すので、
これを条件にしたがって選択し、最後に.with_scope
を呼んでスコープを適用します。
そこで、
with_named_scope
というGemプラグインをつくり、
上述のように処理できるようにしました。
以下のようになります。
1 def gadgets_on_sidebar(place = 'index')
2 case place.to_s
3 when 'index'; Gadget.on_index
4 when 'show'; Gadget.on_show
5 else Gadget.all
6 end.with{active_gadgets + Gadget.mandatories}
7 end
ということで、Rails本家にもpatchを送っておきました。