Class: SimpleImagesDownloader::Downloader

Inherits:
Object
  • Object
show all
Includes:
Validatable
Defined in:
lib/simple_images_downloader/downloader.rb

Overview

Downloader class Responsible for downloading images from URI and placing them to the destination folder allows to use custom client and validators for downloading

Examples:

SimpleImagesDownloader::Downloader.new(uri).download

Instance Method Summary collapse

Methods included from Validatable

#validate!

Constructor Details

#initialize(uri, client = Client.new, validators = [MimeTypeValidator.new]) ⇒ Downloader

Returns a new instance of Downloader.

Parameters:

  • uri (URI)

    URI object from which image will be downloaded

  • client (Client) (defaults to: Client.new)

    Client object for opening the URI. Default: Client.new

  • validators (Array) (defaults to: [MimeTypeValidator.new])

    array of validators for validating the response. Default: [MimeTypeValidator.new]



17
18
19
20
21
# File 'lib/simple_images_downloader/downloader.rb', line 17

def initialize(uri, client = Client.new, validators = [MimeTypeValidator.new])
  @uri        = uri
  @client     = client
  @validators = validators
end

Instance Method Details

#downloadObject

Downloads image from URI and places it to the destination folder

Raises:

See Also:



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/simple_images_downloader/downloader.rb', line 29

def download
  puts "Downloading #{@uri}"

  io = @client.open(@uri)

  raise Errors::EmptyResponse, @uri if io.nil?

  validate!({ path: @uri.to_s, io: io })

  tempfile = StringioToTempfile.convert(io)

  Dispenser.new(tempfile, @uri.path).place

  puts 'Downloading is finished'
ensure
  io&.close
  tempfile&.close
end