Class: Imgin::Image

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

Class Method Summary collapse

Class Method Details



18
19
20
21
22
# File 'lib/imgin.rb', line 18

def extract_links_to_imgs(page)
  links_to_imgs = []
  page.css('li.ld a').each {|link| links_to_imgs << link['href']}
  links_to_imgs
end

.get(search_phrase, size = "") ⇒ Object



46
47
48
49
50
# File 'lib/imgin.rb', line 46

def get(search_phrase, size="")
  links_to_imgs = extract_links_to_imgs(get_search_results(search_phrase, size))
  img_links = parse_image_links(links_to_imgs)
  select_image(reformat_urls(img_links))
end

.get_search_results(search_phrase, size) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/imgin.rb', line 10

def get_search_results(search_phrase, size)
  size_hash = { :small => "&imgsz=icon", :medium => "&imgsz=medium",
              :large => "&imgsz=large", :huge => "&imgsz=wallpaper"}

  search_phrase.gsub!(/\s/) { '+' }
  page = Nokogiri::HTML(open("https://images.search.yahoo.com/search/images?p=#{search_phrase}#{size_hash[size.to_sym]}"))
end


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/imgin.rb', line 24

def parse_image_links(links)
  img_urls = []
  img_url_pattern = /.*(imgurl=)(.*\.(jpg|jpeg|png|gif|svg))/
  links.each do |link|
    link_match = img_url_pattern.match(link)
    if link_match
      img_urls << link_match[2]
    end
  end
  img_urls
end

.reformat_urls(img_urls) ⇒ Object



36
37
38
39
40
# File 'lib/imgin.rb', line 36

def reformat_urls(img_urls)
  img_urls.each do |url|
    url.gsub!(/(%2F)/) { '/' }.gsub!(/(%2520)/) { '%20' }
  end
end

.select_image(img_urls) ⇒ Object



42
43
44
# File 'lib/imgin.rb', line 42

def select_image(img_urls)
  img_urls.sample
end