2008年5月19日 星期一

yield 用在啥時?


目的是想要拿到準確率最高的人的partial, 先從cache 拿, 拿不到再自己生出來

當然可以用一連串的 if, else 來做, 但是這樣便會把邏輯放在controller, 我們的希望是可以把邏輯儘量都放在model裡, 但是有時候又需要controller裡的一東西, 那這時當然就需要傳參數了, 當我們需要的參數一段code, 這時候就需要yield了

== controller ==
#Partial 先去cache 裡拿partial, 希望可以直接拿回需要的東西
@most_popular_users = Partial.get_cache do
users = User.most_accurate_user
@most_popular_users = render_to_string :partial => partial
end

== Partial model ==
def self.get_cache
# 先從cache 拿, 拿的到就直接回家
unless content = get_page_from_cache_or_db(key)
#拿不到就會到這邊來, 用傳進來的code 把需要的內容生出來, 存cache後 丟回去
content = yield
save_page_to_cache_and_db(key,content)
content
end


反正就是為了讓邏輯留在model 用的

沒有留言: