Class: Box::Release::Downloader
- Inherits:
-
Object
- Object
- Box::Release::Downloader
- Defined in:
- lib/box/release/downloader.rb
Instance Attribute Summary collapse
-
#url ⇒ Object
readonly
Returns the value of attribute url.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(url) ⇒ Downloader
constructor
A new instance of Downloader.
- #open(&block) ⇒ Object
- #open_file(&block) ⇒ Object
- #open_http(&block) ⇒ Object
- #send_request(target = url, redirection_count = 0, &block) ⇒ Object
Constructor Details
#initialize(url) ⇒ Downloader
Returns a new instance of Downloader.
9 10 11 |
# File 'lib/box/release/downloader.rb', line 9 def initialize(url) @url = URI.parse url end |
Instance Attribute Details
#url ⇒ Object (readonly)
Returns the value of attribute url.
7 8 9 |
# File 'lib/box/release/downloader.rb', line 7 def url @url end |
Class Method Details
.open(url, &block) ⇒ Object
13 14 15 |
# File 'lib/box/release/downloader.rb', line 13 def self.open(url, &block) new(url).open(&block) end |
Instance Method Details
#open(&block) ⇒ Object
17 18 19 20 21 22 23 |
# File 'lib/box/release/downloader.rb', line 17 def open(&block) if url.scheme == "http" open_http &block else open_file &block end end |
#open_file(&block) ⇒ Object
25 26 27 28 29 30 31 32 33 34 |
# File 'lib/box/release/downloader.rb', line 25 def open_file(&block) content_length = File.size(url.path) File.open(url.path, "r") do |file| downloaded_size = 0 while data = file.read(1024) downloaded_size += data.size yield data, downloaded_size, content_length end end end |
#open_http(&block) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/box/release/downloader.rb', line 36 def open_http(&block) send_request do |response| content_length = nil if response.key?('Content-Length') content_length = response['Content-Length'].to_i end downloaded_size = 0 response.read_body do |data| downloaded_size += data.size yield data, downloaded_size, content_length end end end |
#send_request(target = url, redirection_count = 0, &block) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/box/release/downloader.rb', line 51 def send_request(target = url, redirection_count = 0, &block) raise "Too many redirections, last one was #{target}" if redirection_count > 10 Net::HTTP.start(target.host, target.port) do |http| request = Net::HTTP::Get.new target.path http.request(request) do |response| case response when Net::HTTPSuccess yield response when Net::HTTPMovedPermanently, # 301 Net::HTTPFound, # 302 Net::HTTPSeeOther, # 303 Net::HTTPTemporaryRedirect # 307 send_request URI.parse(response['location']), redirection_count+1, &block else response.error! end end end end |