From 951669e972d77b608ee923979c2e17fa6573c04c Mon Sep 17 00:00:00 2001 From: Jaiden Mispy Date: Wed, 13 Jan 2016 00:58:38 -0800 Subject: [PATCH] Error before archive download if file inaccessible Fixes #85 --- lib/twitter_ebooks/archive.rb | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/lib/twitter_ebooks/archive.rb b/lib/twitter_ebooks/archive.rb index 29829e2..c822fbe 100644 --- a/lib/twitter_ebooks/archive.rb +++ b/lib/twitter_ebooks/archive.rb @@ -50,7 +50,8 @@ module Ebooks @client = client || make_client if File.exists?(@path) - @tweets = JSON.parse(File.read(@path, :encoding => 'utf-8'), symbolize_names: true) + @filetext = File.read(@path, :encoding => 'utf-8') + @tweets = JSON.parse(@filetext, symbolize_names: true) log "Currently #{@tweets.length} tweets for #{@username}" else @tweets.nil? @@ -59,6 +60,21 @@ module Ebooks end def sync + # We use this structure to ensure that + # a) if there's an issue opening the file, we error out before download + # b) if there's an issue during download we restore the original + File.open(@path, 'w') do |file| + begin + sync_to(file) + rescue Exception + file.seek(0) + file.write(@filetext) + raise + end + end + end + + def sync_to(file) retries = 0 tweets = [] max_id = nil @@ -93,9 +109,7 @@ module Ebooks @tweets = tweets.map(&:attrs).each { |tw| tw.delete(:entities) } + @tweets - File.open(@path, 'w') do |f| - f.write(JSON.pretty_generate(@tweets)) - end + file.write(JSON.pretty_generate(@tweets)) end end end