lib/twitter_ebooks/archive.rb in twitter_ebooks-3.1.3 vs lib/twitter_ebooks/archive.rb in twitter_ebooks-3.1.4
- old
+ new
@@ -48,19 +48,35 @@
end
@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?
log "New archive for @#{username} at #{@path}"
end
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
opts = {
@@ -91,12 +107,10 @@
else
@tweets ||= []
@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
end