class BackgroundImages::Downloader

Attributes

download_url[RW]
file_extension[RW]
find_image_of[RW]
save_to_file[RW]

Public Class Methods

new(find_image_of="Brad Pitt's Ghost", save_to_file="") click to toggle source
# File lib/background_images/downloader.rb, line 5
def initialize(find_image_of="Brad Pitt's Ghost", save_to_file="")
  @find_image_of = find_image_of
  @save_to_file  = save_to_file
end

Public Instance Methods

clean() click to toggle source
# File lib/background_images/downloader.rb, line 34
def clean
  `find . -type f -name "*.png" -exec convert {} -strip {} \;`
end
download() click to toggle source
# File lib/background_images/downloader.rb, line 10
def download
  `curl "#{download_url}" > "#{local_file}.#{file_extension}"`
  self
end
standardize(selfie_image) click to toggle source
# File lib/background_images/downloader.rb, line 15
def standardize(selfie_image)
  dimensions = "#{selfie_image.page.width}x#{selfie_image.page.height}"

  `convert #{Shellwords.escape(local_file)}.#{file_extension} -resize '#{dimensions}^' -gravity 'center' -crop '#{dimensions}+0+0' #{Shellwords.escape(local_file)}.#{destination_extension}`

  begin
    image = Magick::Image.read("#{local_file}.#{destination_extension}")
  rescue
  end

  if command_failed? || image.nil?
    get_new_background_image
    download
    standardize(selfie_image)
  end

  self
end

Private Instance Methods

acceptable_extension?(extension) click to toggle source
# File lib/background_images/downloader.rb, line 55
def acceptable_extension?(extension)
  acceptable_extensions.include?(extension.to_s)
end
acceptable_extensions() click to toggle source
# File lib/background_images/downloader.rb, line 51
def acceptable_extensions
  ["jpg", "png"]
end
command_failed?() click to toggle source
# File lib/background_images/downloader.rb, line 39
def command_failed?
  $? != 0
end
destination_extension() click to toggle source
# File lib/background_images/downloader.rb, line 47
def destination_extension
  save_to_file.split(".")[-1] || "png"
end
find_image(method=:first) click to toggle source
# File lib/background_images/downloader.rb, line 67
def find_image(method=:first)
  image = image_finder.find_one(method)

  unless acceptable_extension? file_extension(image["url"])
    return find_image(:sample)
  end

  image["url"]
end
get_new_background_image() click to toggle source

Randomly select a new background image

# File lib/background_images/downloader.rb, line 82
def get_new_background_image
  @download_url = find_image(:sample)
end
image_finder() click to toggle source
# File lib/background_images/downloader.rb, line 77
def image_finder
  @image_finder ||= BackgroundImages::Finder.new(find_image_of)
end
local_file() click to toggle source
# File lib/background_images/downloader.rb, line 43
def local_file
  save_to_file.split(".")[0..-2].join(".")
end