comparison app/models/tweet.rb @ 135:3fc882b0884d

Refactored client initialization
author nanaya <me@nanaya.pro>
date Wed, 13 Dec 2017 02:51:27 +0900
parents 3646b3e319c7
children 59991d10f8a3
comparison
equal deleted inserted replaced
134:3646b3e319c7 135:3fc882b0884d
1 class Tweet 1 class Tweet
2 def initialize(twitter_id)
3 @clients = {}
4 @twitter_id = twitter_id
5 end
6
2 def cache_expires_time 7 def cache_expires_time
3 (15 + rand(15)).minutes 8 (15 + rand(15)).minutes
4 end 9 end
5 10
6 def timeline 11 def timeline
7 start_client_config_id = @client_config_id 12 initial_config_id = client_config_id
8 13
9 @timeline ||= 14 @timeline ||=
10 Rails.cache.fetch({ :timeline => @twitter_id }, :expires_in => cache_expires_time) do 15 Rails.cache.fetch({ :timeline => @twitter_id }, :expires_in => cache_expires_time) do
11 begin 16 begin
12 @client.user_timeline(@twitter_id, :count => 100, :exclude_replies => false, :include_rts => true, :tweet_mode => :extended) 17 client.user_timeline(@twitter_id, :count => 100, :exclude_replies => false, :include_rts => true, :tweet_mode => :extended)
13 rescue Twitter::Error::TooManyRequests 18 rescue Twitter::Error::TooManyRequests
14 next_client_config_id = @client_config_id + 1 19 @client_config_id += 1
15 init_client next_client_config_id
16 20
17 if @client_config_id == start_client_config_id 21 if initial_config_id == client_config_id
18 raise 22 raise
19 else 23 else
20 retry 24 retry
21 end 25 end
22 end 26 end
32 @client.user(@twitter_id) 36 @client.user(@twitter_id)
33 end 37 end
34 end 38 end
35 end 39 end
36 40
37 def initialize(twitter_id) 41 def client
38 @client = init_client 42 @clients[client_config_id] ||=
39 @twitter_id = twitter_id 43 Twitter::REST::Client.new do |config|
44 $cfg[:twitter][client_config_id].each do |cfg_key, cfg_value|
45 config.public_send("#{cfg_key}=", cfg_value)
46 end
47 end
40 end 48 end
41 49
42 def init_client(config_id = 0) 50 def client_config_id
43 @client_config_id = config_id 51 @client_config_id ||= 0
44 config_hash_key = "twitter#{config_id}".to_sym
45 52
46 return init_client(0) if $cfg[config_hash_key].nil? && config_id != 0 53 @client_config_id % $cfg[:twitter].size
47
48 @client = Twitter::REST::Client.new do |config|
49 $cfg[config_hash_key].each do |cfg_key, cfg_value|
50 config.public_send("#{cfg_key}=", cfg_value)
51 end
52 end
53 end 54 end
54 end 55 end