PageRenderTime 77ms CodeModel.GetById 49ms app.highlight 6ms RepoModel.GetById 21ms app.codeStats 0ms

/lib/duck_duck_go.rb

https://github.com/andrewrjones/ruby-duck-duck-go
Ruby | 58 lines | 36 code | 11 blank | 11 comment | 2 complexity | 88afab078cfea5afe169c45d860742cd MD5 | raw file
 1# Author: Andrew Jones <http://andrew-jones.com>
 2# The license of this source is MIT Licence
 3
 4module DuckDuckGo
 5  
 6  require 'rubygems'
 7  require 'uri'
 8  require 'httpclient'
 9  require 'json'
10  require 'duck_duck_go/zero_click_info'
11
12  # see DuckDuckGo::Main.new
13  def self.new(*params)
14    DuckDuckGo::Main.new(*params)
15  end
16  
17  class Main
18    
19    API_URL = 'http://api.duckduckgo.com/'
20    API_URL_SECURE = 'https://api.duckduckgo.com/'
21    
22    # Create a new instance.
23    # It is recommended to pass in a meaningful user agent.
24    # Defaults to using the secure api (https)
25    def initialize(http_agent_name = 'DuckDuckGo.rb', secure = true)
26      if secure
27        @url = API_URL_SECURE
28      else
29        @url = API_URL
30      end
31      @http = HTTPClient.new(:agent_name => http_agent_name)
32    end
33    
34    # Run a query against Duck Duck Go
35    # Returns an instance of DuckDuckGo::ZeroClickInfo
36    def zeroclickinfo(query, skip_disambiguation = false)
37      args = {
38        'q' => query,
39        'o' => 'json'
40      }
41      if(skip_disambiguation)
42        args['d'] = 1
43      end
44      
45      data = @http.get_content(@url, args)
46  
47      # parse the JSON and return an instance
48      # of the ZeroClickInfo class
49      DuckDuckGo::ZeroClickInfo.by(JSON.parse(data))
50    end
51  
52    # Alias for DuckDuckGo::Main.zeroclickinfo
53    def zci(*params)
54      self.zeroclickinfo(*params)
55    end
56  end
57  
58end