【问题标题】:Can I cache a result using the Twitter gem? (Rails 4)我可以使用 Twitter gem 缓存结果吗? (导轨 4)
【发布时间】:2014-02-17 07:20:44
【问题描述】:

我正在使用Twitter Gem

我的模特:

class TweetyClass
  def initialize
    @client = Twitter::REST::Client.new do |config|
      config.consumer_key        = TWITTER_CONFIG['consumer_key']
      config.consumer_secret     = TWITTER_CONFIG['consumer_secret']
      config.access_token        = TWITTER_CONFIG['access_token']
      config.access_token_secret = TWITTER_CONFIG['access_token_secret']
    end
  end

  def user_timeline
    @client.user_timeline( count: 2)
  end
end

我的控制器:

def tweets
  @tweets = TweetyClass.new.user_timeline
end

我的看法:

<% @tweets.each do |tweet| %>

  <li><%= tweet.foo%></li>

<% end %>

有没有办法缓存结果,所以每次我调用 user_timeline 时,它都会从 app/app 变量中获取结果,而不是去 Twitter 并获取推文的时间线。

抱歉,如果我没有使用正确的术语;我是缓存主题的新手。本质上,我想做的是提高我的应用程序的速度,而似乎会减慢速度的一件事是使用 user_timeline 方法检索推文所需的时间。我假设这是因为它每次都从 Twitter 中检索它,我认为缓存可能会有所帮助。

【问题讨论】:

    标签: ruby-on-rails ruby caching twitter ruby-on-rails-4


    【解决方案1】:

    是的,你可以使用 memcached 来做到这一点,但你必须先设置你的环境。

    1) 安装 memcached

    sudo apt-get install memcached (ubuntu)
    brew install memcached (mac os x)
    

    2) 将 dalli 添加到 => Gemfile

    gem 'dalli'
    

    3) 改变环境/development.rb

    config.action_controller.perform_caching = true
    

    4) 最后是 your_controller.rb

    @tweets = Rails.cache.fetch("your_unique_cache_key_name") do
      TweetyClass.new.user_timeline
    end
    

    您可以从this 教程中了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-24
      • 2013-08-31
      • 1970-01-01
      • 2020-04-30
      • 2011-03-26
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多