Class: Finder

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

Instance Method Summary collapse

Instance Method Details

#find(options) ⇒ Object

keyword, url, limit, engine, res_per_page



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/uk_ranking.rb', line 52

def find(options) #keyword, url, limit, engine, res_per_page
 options[:keyword].gsub!(/\s/, '+')
 request_url, results_selector, cite_selector = case options[:engine].to_sym
 when :bing
   ["http://www.bing.com/search?q=#{options[:keyword]}&count=#{options[:res_per_page]}&first=", '#wg0 > li', 'cite']
 when :google
   ["http://www.google.co.uk/search?q=#{options[:keyword]}&num=#{options[:res_per_page]}&start=", '#ires > ol > li', 'cite']
 when :googleUS
   ["http://www.google.com/search?q=#{options[:keyword]}&num=#{options[:res_per_page]}&start=", '#ires > ol > li', 'cite']
 when :yahoo
   ["http://search.yahoo.com/search?p=#{options[:keyword]}&n=#{options[:res_per_page]}&b=", '#web > ol > li', 'span']
 end

 count, rank = 0, nil

 loop {
   html_response = Net::HTTP.get_response(URI.parse("#{request_url}#{count}")).body
   html_results = Nokogiri.parse(html_response).css(results_selector)
 
  if html_results.detect{ |result| result.css("#productbox") }
  #if html_results.index(html_results.detect{ |result| result.css(cite_selector).text.match Regexp.new(options[:url]) })
         
    rank = html_results.index(html_results.detect{ |result| result.css(cite_selector).text.match Regexp.new(options[:url]) })

    if count > options[:limit]
       break
    elsif rank
       rank += count - 1
       break
    end
     count += options[:res_per_page]
     
  else
    rank = html_results.index(html_results.detect{ |result| result.css(cite_selector).text.match Regexp.new(options[:url]) })

    if count > options[:limit]
      break
    elsif rank
      rank += count
      break
    end
    count += options[:res_per_page]
 end#If HTML
 }
 rank ? rank.next : nil
end