class Fotofetch::Fetch

Public Instance Methods

add_sources(urls) click to toggle source

Adds root urls as hash keys

# File lib/fotofetch.rb, line 63
def add_sources(urls)
  results = {}.compare_by_identity
  urls.each { |link| results[link.split("/")[2]] = link}
  results
end
height_ok?(sizes) click to toggle source
# File lib/fotofetch.rb, line 57
def height_ok?(sizes)
  height = sizes[1][1] - sizes[0][1]
  (0 < height && height < sizes[1][1]) || height > (sizes[1][1] * 2)
end
pluck_imgs(urls, amount, width, height) click to toggle source
# File lib/fotofetch.rb, line 26
def pluck_imgs(urls, amount, width, height)
  urls = (urls.select { |link| link.include?(".jpg") || link.include?(".png") })
  restrict_dimensions(urls, width, height, amount) if restrictions?(width, height)
  @results = urls if @results.empty?
  urls = @results[0..(amount-1)] # selects only number of links desired, default is 1.
  add_sources(urls)
end
pluck_urls(page, amount, width, height) click to toggle source
# File lib/fotofetch.rb, line 20
def pluck_urls(page, amount, width, height)
  urls = []
  page.links.each { |link| urls << link.href } # gathers all urls.
  pluck_imgs(urls, amount, width, height)
end
restrict_dimensions(urls, width, height, amount) click to toggle source
# File lib/fotofetch.rb, line 38
def restrict_dimensions(urls, width, height, amount)
  urls.each do |link|
    select_links(link, width, height) unless @results.length >= amount
  end
end
restrictions?(width, height) click to toggle source
# File lib/fotofetch.rb, line 34
def restrictions?(width, height)
  (width != 9999 || height!= 9999) ? true : false
end
save_images(urls, file_path) click to toggle source

takes an array of links

# File lib/fotofetch.rb, line 70
def save_images(urls, file_path)
  urls.each_with_index do |url, i|
    open("#{@query.gsub(' ', '-')}_#{i}.jpg", 'wb') do |file|
      file << open(url).read
    end
  end
end
scrape(topic, amount, width, height) click to toggle source
# File lib/fotofetch.rb, line 14
def scrape(topic, amount, width, height)
  agent = Mechanize.new
  page = agent.get("http://www.bing.com/images/search?q=#{topic}")
  pluck_urls(page, amount, width, height)
end
width_ok?(sizes) click to toggle source
# File lib/fotofetch.rb, line 52
def width_ok?(sizes)
  width = sizes[1][0] - sizes[0][0]
  (0 < width && width < sizes[1][0]) || width > (sizes[1][0] * 2)
end