2011-10-11 98 views
4

我是Ruby(和Rails)的新手,希望你能幫我澄清一些我正在經歷的困惑。用Dalli緩存Twitter結果

我正在嘗試將Twitter gem整合到我的網站中,以便獲取用戶的最新推文,並獲取其個人資料圖片的鏈接。在一小時之內,創業板運作良好,直到(我認爲是)第100次API調用之後,Twitter將會阻止你。

從我收集的內容中,我需要使用memcache緩存大約1分鐘的結果。有一些偉大的pseudocode here,但不幸的是,它有點在我的頭上。我希望能得到一些更具體的細節。

目前,我不確定在哪裏放置該代碼?我想在應用程序佈局視圖中顯示Twitter信息,那麼它會進入application_helper.rb文件中的方法嗎?

我最好的嘗試解決這個問題導致下面的代碼引發了一個「Missing Helper File」錯誤。

module ApplicationHelper 
    require "memcache" 

    def twitter 
    cache = MemCache.new 
    twitter = cache.get("twitter").first 
    if twitter.nil? 
     begin 
     twitter = Twitter.user("TwitterName") 
     cache.set("twitter", twitter, :expires_in => 1.minute) if twitter 
     rescue 
     twitter = default 
     end 
    end 
    return twitter 
    end 
end 

回答

5

首先啓用緩存和memcache爲您的環境中(例如配置/環境/ production.rb)

# Use a different cache store in production 
config.cache_store = :mem_cache_store 

然後在要顯示鳴叫認爲做這樣的事

<% cache("tweets", :expires_in => 42.minutes) do %> 
<% Twitter.user_timeline("User").each do %> 
    ..... 
    <% end %> 
<% end %> 
+0

像魅力一樣工作,謝謝。對於遲到的回覆,我的網絡出現故障。出於好奇,使用memcache而不是dalli有什麼好處嗎? – Ian

+0

你是指舊的memcache驅動程序和dalli之間的區別? – bandito

+0

是的,我想。那麼他們只是不同的包裝? – Ian