view app/models/tweet.rb @ 77:fc2bc34e6d89

Don't loop if twitter0 is not configured
author nanaya <me@myconan.net>
date Sun, 26 Jun 2016 16:49:15 +0900
parents 0c023d35cd80
children 924b3a4ed3ef
line wrap: on
line source

class Tweet
  def timeline(options = {})
    start_client_config_id = @client_config_id

    begin
      @timeline ||=
        Rails.cache.fetch({ :timeline => @twitter_id, :options => options.dup }, :expires_in => 5.minutes) do
          @client.user_timeline(@twitter_id, options)
        end
    rescue Twitter::Error::TooManyRequests
      next_client_config_id = @client_config_id + 1
      init_client next_client_config_id
      retry unless @client_config_id == start_client_config_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 = 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