module Trollme::Downloader

Constants

OpenFile
SaveFile
SetFolder

Attributes

file[R]
url[R]

Private Class Methods

download_image_and_return_path() click to toggle source
# File lib/trollme/downloader.rb, line 45
def download_image_and_return_path
  new_file = File.open(file, 'wb') { |new_file| write_image(new_file) }
  get_existing_file(new_file.path)
rescue Errno::ENOENT
  rollback
  raise SaveFile
end
get_existing_file(path) click to toggle source
# File lib/trollme/downloader.rb, line 41
def get_existing_file(path)
  "#{Dir.pwd}/#{path}"
end
rollback() click to toggle source
# File lib/trollme/downloader.rb, line 63
def rollback
  File.delete(file)
end
set_defaults(topic) click to toggle source
# File lib/trollme/downloader.rb, line 30
def set_defaults(topic)
  @file = topic['file']
  @url = topic['url']
end
set_folder() click to toggle source
# File lib/trollme/downloader.rb, line 35
def set_folder
  Dir.chdir(File.expand_path('~/Downloads'))
rescue Errno::ENOENT
  raise SetFolder
end
write_image(file) click to toggle source
# File lib/trollme/downloader.rb, line 53
def write_image(file)
  file << open(url).read
rescue Errno::ENOENT
  rollback
  raise OpenFile
rescue SocketError
  rollback
  raise OpenFile
end

Public Instance Methods

call(topic) click to toggle source
# File lib/trollme/downloader.rb, line 11
def call(topic)
  set_defaults(topic)
  set_folder
  if File.exist?(@file)
    get_existing_file(@file)
  else
    download_image_and_return_path
  end
rescue SetFolder
  abort "Something went wrong to set your folder's download directory"
rescue OpenFile
  abort 'Was not possible to open the image from internet'
rescue SaveFile
  abort 'Was not possible to create a file'
end