Module: DuckDuckGo

Defined in:
lib/duckduckgo/search.rb,
lib/duckduckgo/result.rb,
lib/duckduckgo/version.rb

Overview

The DuckDuckGo module.

Defined Under Namespace

Classes: SearchResult

Constant Summary collapse

RESOURCE_URL =

The suffix for the URL that we visit when querying DuckDuckGo.

'https://duckduckgo.com/html/?q='
VERSION =
'0.1.8'

Class Method Summary collapse

Class Method Details

.search(hash) ⇒ Object

Searches DuckDuckGo for the given query string. This function returns an array of SearchResults.

Parameters:

  • hash (Hash)

    a hash containing the query string and possibly other configuration settings.

Raises:

  • (Exception)

    if there is an error scraping DuckDuckGo for the search results.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/duckduckgo/search.rb', line 19

def self.search(hash)

  results = []

  raise 'Hash does not contain a query string.' if hash[:query].nil?
  html = URI.open("#{RESOURCE_URL}#{CGI::escape(hash[:query])}")

  document = Nokogiri::HTML(html)

  document.css('.results_links').each do |result|
    title_element = result.css('.result__a').first
    raise 'Could not find result link element!' if title_element.nil?

    title = title_element.text
    raise 'Could not find result title!' if title.nil?

    uri = title_element['href']
    raise 'Could not find result URL!' if uri.nil?

    description_element = result.css('.result__snippet').first
    raise 'Could not find result description element!' if description_element.nil?

    description = description_element.text
    raise 'Could not find result description!' if description.nil?

    results << SearchResult.new(uri, title, description)
  end

  return results
end