diff app/models/tweet.rb @ 158:74422bae017d

Always use canonical id and turn cache time generator a class method
author nanaya <me@nanaya.pro>
date Fri, 03 Aug 2018 01:38:53 +0900
parents 6e6051cd9cca
children 4e4195e60c2b
line wrap: on
line diff
--- a/app/models/tweet.rb	Sat Jul 28 03:42:23 2018 +0900
+++ b/app/models/tweet.rb	Fri Aug 03 01:38:53 2018 +0900
@@ -6,27 +6,28 @@
     :tweet_mode => :extended,
   }
 
+  def self.cache_expires_time
+    (15 + rand(15)).minutes
+  end
+
   def initialize(twitter_id)
     @clients = {}
     @twitter_id = twitter_id
   end
 
-  def cache_expires_time
-    (15 + rand(15)).minutes
-  end
-
-  def cache_key
-    "timeline:v2:#{@twitter_id}/#{Base64.urlsafe_encode64 @twitter_id.to_s}"
+  def id
+    user.id
   end
 
   def timeline
     if @timeline.nil?
-      raw = Rails.cache.fetch(cache_key, :expires_in => cache_expires_time) do
-        client_try(:user_timeline, @twitter_id, TIMELINE_OPTIONS).tap do |data|
+      cache_key = "timeline:v2:#{id}/#{Base64.urlsafe_encode64 id.to_s}"
+      raw = Rails.cache.fetch(cache_key, :expires_in => self.class.cache_expires_time) do
+        client_try(:user_timeline, id, TIMELINE_OPTIONS).tap do |data|
           if data[:result] == :ok
-            if data[:data].any? && data[:data].first.user.id != @twitter_id
+            if data[:data].any? && data[:data].first.user.id != id
               wrong_user = data[:data].first.user
-              Rails.logger.warn "Wrong timeline data. Requested: #{@twitter_id}, got: #{wrong_user.id} (#{wrong_user.name.printable})"
+              throw "Wrong timeline data. Requested: #{id}, got: #{wrong_user.id} (#{wrong_user.name.printable})"
             end
 
             data[:data] = data[:data].select do |tweet|
@@ -46,9 +47,7 @@
 
   def user
     if @user.nil?
-      return timeline.first.user if timeline.any?
-
-      raw = Rails.cache.fetch("user:v1:#{@twitter_id}", :expires_in => cache_expires_time) do
+      raw = Rails.cache.fetch("user:v1:#{@twitter_id}", :expires_in => self.class.cache_expires_time) do
         client_try :user, @twitter_id
       end
 
@@ -90,8 +89,9 @@
   end
 
   def client_config_id
-    @client_config_id ||= 0
+    @client_config_count ||= $cfg[:twitter].size
+    @client_config_id ||= rand(@client_config_count)
 
-    @client_config_id %= $cfg[:twitter].size
+    @client_config_id %= @client_config_count
   end
 end