Browse files

fix up async example to have a timeout and some more helpful status o…

…utput
  • Loading branch information...
1 parent 3c7b34f commit eae1617ea1ae6184e0922172518cfcfc32a5431a @janxious janxious committed Jun 21, 2011
Showing with 21 additions and 11 deletions.
  1. +21 −11 ruby/async_ruby_example.rb
View
32 ruby/async_ruby_example.rb
@@ -1,29 +1,39 @@
require 'rubygems'
require 'doc_raptor'
+TEN_SECONDS = 10
+FIVE_MINUTES = 300
+
DocRaptor.api_key "YOUR_API_KEY_HERE"
pdf_html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html lang="en"><body><a href="http://google.com">google</a></body></html>'
+def pretty_time; Time.now.strftime("%I:%M:%S %p"); end
+def print_status(status = {}); puts "#{pretty_time} - Status: #{status['status']}";end
+
status_id = DocRaptor.create(:document_content => pdf_html,
:name => "docraptor_sample.pdf",
:document_type => "pdf",
- :test => false,
+ :test => true,
:async => true)
-status = { }
+# This timeout is 5 minutes.
+# If there is no load on the background processors, this test should take (far) less than 20s. It's possible production will be backed up with real jobs, hence the timeout.
+timeout_time = Time.now + FIVE_MINUTES
+
+status = {'status' => 'queued'}
-status['status'] = 'queued'
-while (status['status'] == 'queued' || status['status'] == 'working')
- sleep(10)
- status = DocRaptor.status
+print_status(status)
+while !(['completed','failed'].include? status['status']) && Time.now <= timeout_time
+ sleep TEN_SECONDS
+ status = DocRaptor.status(status_id)
+ print_status(status)
end
if status['status'] == 'completed'
- File.open("docraptor_sample.pdf", "w+") do |f|
- f.write DocRaptor.download
+ file = DocRaptor.download(status['download_key'])
+ File.open("docraptor_sample.pdf", "w+b") do |f|
+ f.write file.response.body
end
-else
- puts "There was an error generating the document:\n#{status['message']}\n"
- puts "#{status['validation_errors']}\n" if status['validation_errors']
+ puts "#{pretty_time} - File downloaded to docraptor_sample.pdf"
end

0 comments on commit eae1617

Please sign in to comment.