Class: Railsmdb::Downloader

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

Overview

A utility class for downloading a file from a given URL.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, destination) ⇒ Downloader

Create a new Downloader object.

Parameters:

  • url (String)

    the url to fetch from

  • destination (String)

    the location to write to



29
30
31
32
# File 'lib/railsmdb/downloader.rb', line 29

def initialize(url, destination)
  @url = url
  @destination = destination
end

Instance Attribute Details

#destinationString (readonly)

Returns where the file should be saved to.

Returns:

  • (String)

    where the file should be saved to.



12
13
14
# File 'lib/railsmdb/downloader.rb', line 12

def destination
  @destination
end

#urlString (readonly)

Returns the url to download from.

Returns:

  • (String)

    the url to download from



9
10
11
# File 'lib/railsmdb/downloader.rb', line 9

def url
  @url
end

Class Method Details

.fetch(url, destination, &callback) ⇒ Object

A helper method for fetching the file in a single call.

Parameters:

  • url (String)

    the url to fetch from

  • destination (String)

    the location to write to

  • callback (Proc)

    a callback block that is invoked with the current total number of bytes read, as each chunk is read from the stream.



21
22
23
# File 'lib/railsmdb/downloader.rb', line 21

def self.fetch(url, destination, &callback)
  new(url, destination).fetch(&callback)
end

Instance Method Details

#fetchObject

Perform the fetch, pulling from the url and writing to the destination.



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/railsmdb/downloader.rb', line 35

def fetch
  File.open(destination, 'w:BINARY') do |io|
    connection.get(url) do |req|
      req.options.on_data = lambda do |chunk, total, _env|
        yield total if block_given?
        io << chunk
      end
    end
  end

  true
end