view app/models/tweet.rb @ 48:8983c426e256

Prevent exploding on empty timeline.
author nanaya <me@myconan.net>
date Thu, 23 Apr 2015 16:14:35 +0900
parents e5082c4c234d
children 1161ad2a4390
line wrap: on
line source

class Tweet
  def timeline
    @timeline ||=
      Rails.cache.fetch({ :timeline => @twitter_id }, :expires_in => 5.minutes) do
        @client.user_timeline(@twitter_id)
      end
  end

  def user
    @user ||=
      if timeline.any?
        timeline.first.user
      else
        Rails.cache.fetch({ :user => @twitter_id }, :expires_in => 5.minutes) do
          @client.user(@twitter_id)
        end
      end
  end

  def initialize(twitter_id)
    @client = Twitter::REST::Client.new do |config|
      CFG[:twitter].each do |cfg_key, cfg_value|
        config.public_send("#{cfg_key}=", cfg_value)
      end
    end
    @twitter_id = twitter_id
  end
end