# HG changeset patch # User nanaya # Date 1513114267 -32400 # Node ID c791b6bfeeda0fb3f2a975f09d5815434766c79f # Parent 1925b08153dca7dbc83d845a637820d3d18234a4 More refactors diff -r 1925b08153dc -r c791b6bfeeda app/models/tweet.rb --- a/app/models/tweet.rb Wed Dec 13 06:10:13 2017 +0900 +++ b/app/models/tweet.rb Wed Dec 13 06:31:07 2017 +0900 @@ -16,52 +16,39 @@ end def timeline - initial_config_id = client_config_id - - @timeline ||= - Rails.cache.fetch("timeline:v1:#{@twitter_id}", :expires_in => cache_expires_time) do - begin - timeline = client.user_timeline(@twitter_id, TIMELINE_OPTIONS) - rescue Twitter::Error::TooManyRequests - @client_config_id += 1 - - if initial_config_id == client_config_id - raise - else - retry + if @timeline.nil? + raw = Rails.cache.fetch("timeline:v2:#{@twitter_id}", :expires_in => cache_expires_time) do + client_try(:user_timeline, @twitter_id, TIMELINE_OPTIONS).tap do |data| + if data[:result] == :ok + data[:data] = data[:data].select do |tweet| + tweet.retweeted_status.nil? || tweet.user.id != tweet.retweeted_status.user.id + end.map { |tweet| tweet.to_h } end - rescue Twitter::Error::NotFound - data = { :result => :not_found } end + end - data || { - :result => :ok, - :timeline => timeline.select do |tweet| - tweet.retweeted_status.nil? || tweet.user.id != tweet.retweeted_status.user.id - end.map do |tweet| - # Fails when there's Twitter::NullObject initiated somewhere in previous select - # Reference: https://github.com/sferik/twitter/issues/892 - tweet.to_h - end, - } - end.tap do |data| - raise Twitter::Error::NotFound if data[:result] == :not_found + raise Twitter::Error::NotFound if raw[:result] == :not_found - data[:timeline_parsed] = data[:timeline].map do |tweet_hash| - Twitter::Tweet.new(tweet_hash) - end - end[:timeline_parsed] + @timeline = raw[:data].map { |tweet_hash| Twitter::Tweet.new(tweet_hash) } + end + + @timeline end def user - @user ||= - if timeline.any? - timeline.first.user - else - Rails.cache.fetch("user:v1:#{@twitter_id}", :expires_in => cache_expires_time) do - client.user(@twitter_id) - end + if @user.nil? + return timeline.first.user if timeline.any? + + raw = Rails.cache.fetch("user:v1:#{@twitter_id}", :expires_in => cache_expires_time) do + client_try :user, @twitter_id end + + raise Twitter::Error::NotFound if raw[:result] == :not_found + + @user = raw[:data] + end + + @user end def client @@ -73,6 +60,26 @@ end end + def client_try(method, *args) + initial_config_id = client_config_id + + begin + data = client.public_send method, *args + rescue Twitter::Error::TooManyRequests + @client_config_id += 1 + + if initial_config_id == client_config_id + raise + else + retry + end + rescue Twitter::Error::NotFound + return { :result => :not_found } + end + + { :result => :ok, :data => data } + end + def client_config_id @client_config_id ||= 0