Class: CarrierWave::Downloader::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/carrierwave/downloader/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uploader) ⇒ Base

Returns a new instance of Base.



10
11
12
# File 'lib/carrierwave/downloader/base.rb', line 10

def initialize(uploader)
  @uploader = uploader
end

Instance Attribute Details

#uploaderObject (readonly)

Returns the value of attribute uploader.



8
9
10
# File 'lib/carrierwave/downloader/base.rb', line 8

def uploader
  @uploader
end

Instance Method Details

#download(url, remote_headers = {}) ⇒ Object

Downloads a file from given URL and returns a RemoteFile.

Parameters

url (String)

The URL where the remote file is stored

remote_headers (Hash)

Request headers



22
23
24
25
26
27
28
29
30
31
# File 'lib/carrierwave/downloader/base.rb', line 22

def download(url, remote_headers = {})
  headers = remote_headers.
    reverse_merge('User-Agent' => "CarrierWave/#{CarrierWave::VERSION}")
  begin
    file = OpenURI.open_uri(process_uri(url.to_s), headers)
  rescue StandardError => e
    raise CarrierWave::DownloadError, "could not download file: #{e.message}"
  end
  CarrierWave::Downloader::RemoteFile.new(file)
end

#process_uri(uri) ⇒ Object

Processes the given URL by parsing and escaping it. Public to allow overriding.

Parameters

url (String)

The URL where the remote file is stored



40
41
42
43
44
45
46
47
# File 'lib/carrierwave/downloader/base.rb', line 40

def process_uri(uri)
  uri_parts = uri.split('?')
  encoded_uri = Addressable::URI.parse(uri_parts.shift).normalize.to_s
  encoded_uri << '?' << URI.encode(uri_parts.join('?')) if uri_parts.any?
  URI.parse(encoded_uri)
rescue URI::InvalidURIError, Addressable::URI::InvalidURIError
  raise CarrierWave::DownloadError, "couldn't parse URL: #{uri}"
end