Class: Bataille::Search

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

Defined Under Namespace

Classes: LimitError

Constant Summary collapse

SEARCH_URL_PREFIX =
"http://www.google.co.jp/search"
MAX_SEARCH_LIMIT =
50

Class Method Summary collapse

Class Method Details

.fetch_result(word, start = 0) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/bataille/search.rb', line 22

def fetch_result(word, start=0)
  charset = nil
  html = open(search_url(word, start)) do |f|
    charset = f.charset
    f.read
  end
  doc = Nokogiri::HTML.parse(html, nil, charset)
  doc.css('.g').each_with_index.map do |result, i|
    Site.new(
      rank: i+1+start,
      keyword: word,
      title: result.css('.r').text,
      url: result.css('.kv').search('cite').text,
      description: result.css('.st').text
    )
  end
end

.google_search(word, limit = 10) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/bataille/search.rb', line 11

def google_search(word, limit=10)
  unless (1..MAX_SEARCH_LIMIT).include?(limit)
    raise LimitError, limit > MAX_SEARCH_LIMIT ? "search results should be under 50" : "something wrong with limit parameter"
  end
  results = 0.upto(fetch_times_for(limit)).map do |n|
    fetch_result(word, n*10)
  end.inject(:+)

  SearchResult.new(results[0..(limit-1)], word)
end