lib/bearcat/client/reports.rb in bearcat-1.3.2 vs lib/bearcat/client/reports.rb in bearcat-1.3.3

- old
+ new

@@ -1,5 +1,7 @@ +require 'csv' + module Bearcat class Client < Footrest::Client module Reports def report_list(account) @@ -20,8 +22,37 @@ def delete_report(account, report_name, report_id) delete("/api/v1/accounts/#{account}/reports/#{report_name}/#{report_id}") end + def download_report(url, save_location=nil) + #This method takes the verified URL returned in a Canvas report (attachment['url']), and if + #a save_location is included, it will download it in chunks to the disk to save memory. You + #can also download the report to memory if you do not include a save location. + attempts = 0 + begin + uri = URI.parse(url) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true if url.start_with?('https') + response = http.head(uri.to_s) + url = response['Location'] + attempts += 1 + end while attempts <= 5 && (response.code == '301' || response.code == '302' || response.code == '307') + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true if uri.to_s.start_with?('https') + if save_location + File.open(save_location, 'wb') do |file| + http.request_get(uri.to_s) do |resp| + resp.read_body do |segment| + file.write(segment) + end + end + end + else + response = http.request_get(uri.to_s) + CSV.parse(response.read_body, headers: true) + end + end + end end -end \ No newline at end of file +end