Class: PRSS::Downloader

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(links) ⇒ Downloader

Returns a new instance of Downloader.



7
8
9
# File 'lib/prss/downloader.rb', line 7

def initialize(links)
  @links = links
end

Class Method Details

.verify!(output_path) ⇒ Object



11
12
13
14
15
# File 'lib/prss/downloader.rb', line 11

def self.verify!(output_path)
  output = Pathname.new(output_path).expand_path
  raise 'output path is not directory' unless output.directory?
  output
end

Instance Method Details

#download_to(output_path) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/prss/downloader.rb', line 17

def download_to(output_path)
  output = self.class.verify!(output_path)

  @files = @links.each.map do |uri|
    response = Net::HTTP.get_response(uri)
    save_file(response, output)
  end.compact
end

#save_file(response, output) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/prss/downloader.rb', line 26

def save_file(response, output)
  filename = response['Content-Disposition'][/filename="(.+)"$/ ,1]
  file = output.join(filename)

  return if file.exist?

  open(file, 'wb') do |file|
    body = response.body
    file.write(body)
  end

  filename
end