view app/models/tweet.rb @ 134:3646b3e319c7

Only try/catch the tweet downloading part
author nanaya <me@nanaya.pro>
date Wed, 13 Dec 2017 02:28:34 +0900
parents 8b2d770160e3
children 3fc882b0884d
line wrap: on
line source

class Tweet
  def cache_expires_time
    (15 + rand(15)).minutes
  end

  def timeline
    start_client_config_id = @client_config_id

    @timeline ||=
      Rails.cache.fetch({ :timeline => @twitter_id }, :expires_in => cache_expires_time) do
        begin
          @client.user_timeline(@twitter_id, :count => 100, :exclude_replies => false, :include_rts => true, :tweet_mode => :extended)
        rescue Twitter::Error::TooManyRequests
          next_client_config_id = @client_config_id + 1
          init_client next_client_config_id

          if @client_config_id == start_client_config_id
            raise
          else
            retry
          end
        end
      end
  end

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

  def initialize(twitter_id)
    @client = init_client
    @twitter_id = twitter_id
  end

  def init_client(config_id = 0)
    @client_config_id = config_id
    config_hash_key = "twitter#{config_id}".to_sym

    return init_client(0) if $cfg[config_hash_key].nil? && config_id != 0

    @client = Twitter::REST::Client.new do |config|
      $cfg[config_hash_key].each do |cfg_key, cfg_value|
        config.public_send("#{cfg_key}=", cfg_value)
      end
    end
  end
end