changeset 48:8983c426e256

Prevent exploding on empty timeline.
author nanaya <me@myconan.net>
date Thu, 23 Apr 2015 16:14:35 +0900
parents e5082c4c234d
children 929218b3b2e2
files app/controllers/tweets_controller.rb app/models/tweet.rb app/views/tweets/show.atom.builder test/controllers/tweets_controller_test.rb
diffstat 4 files changed, 20 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/app/controllers/tweets_controller.rb	Thu Apr 23 16:05:08 2015 +0900
+++ b/app/controllers/tweets_controller.rb	Thu Apr 23 16:14:35 2015 +0900
@@ -3,9 +3,9 @@
   end
 
   def show
-    @tweets = Tweet.new(params[:id]).timeline
-
-    @user = @tweets.first.user
+    client = Tweet.new(params[:id])
+    @tweets = client.timeline
+    @user = client.user
   rescue Twitter::Error::NotFound
     head :not_found
   rescue Twitter::Error::Unauthorized
--- a/app/models/tweet.rb	Thu Apr 23 16:05:08 2015 +0900
+++ b/app/models/tweet.rb	Thu Apr 23 16:14:35 2015 +0900
@@ -6,6 +6,17 @@
       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 = Twitter::REST::Client.new do |config|
       CFG[:twitter].each do |cfg_key, cfg_value|
--- a/app/views/tweets/show.atom.builder	Thu Apr 23 16:05:08 2015 +0900
+++ b/app/views/tweets/show.atom.builder	Thu Apr 23 16:14:35 2015 +0900
@@ -1,6 +1,6 @@
 atom_feed do |feed|
   feed.title "#{@user.name} (@#{@user.screen_name})"
-  feed.updated @tweets.first.created_at
+  feed.updated @tweets.first.try(:created_at) || Time.at(0)
 
   @tweets.each do |tweet|
     feed.entry tweet, :url => tweet.uri, :updated => tweet.created_at do |entry|
--- a/test/controllers/tweets_controller_test.rb	Thu Apr 23 16:05:08 2015 +0900
+++ b/test/controllers/tweets_controller_test.rb	Thu Apr 23 16:14:35 2015 +0900
@@ -6,6 +6,11 @@
     assert_response :success
   end
 
+  test "does not explode on empty timeline" do
+    get :show, :id => "nanaya_t_empty", :format => :atom
+    assert_response :success
+  end
+
   test "should get index" do
     get :index
     assert_response :success