Error before archive download if file inaccessible

Fixes #85
This commit is contained in:
Jaiden Mispy 2016-01-13 00:58:38 -08:00
parent 8320576ab3
commit 951669e972

View file

@ -50,7 +50,8 @@ module Ebooks
@client = client || make_client @client = client || make_client
if File.exists?(@path) 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}" log "Currently #{@tweets.length} tweets for #{@username}"
else else
@tweets.nil? @tweets.nil?
@ -59,6 +60,21 @@ module Ebooks
end end
def sync 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 retries = 0
tweets = [] tweets = []
max_id = nil max_id = nil
@ -93,9 +109,7 @@ module Ebooks
@tweets = tweets.map(&:attrs).each { |tw| @tweets = tweets.map(&:attrs).each { |tw|
tw.delete(:entities) tw.delete(:entities)
} + @tweets } + @tweets
File.open(@path, 'w') do |f| file.write(JSON.pretty_generate(@tweets))
f.write(JSON.pretty_generate(@tweets))
end
end end
end end
end end