PageRenderTime 26ms CodeModel.GetById 30ms RepoModel.GetById 1ms 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. module DuckDuckGo
  4. require 'rubygems'
  5. require 'uri'
  6. require 'httpclient'
  7. require 'json'
  8. require 'duck_duck_go/zero_click_info'
  9. # see DuckDuckGo::Main.new
  10. def self.new(*params)
  11. DuckDuckGo::Main.new(*params)
  12. end
  13. class Main
  14. API_URL = 'http://api.duckduckgo.com/'
  15. API_URL_SECURE = 'https://api.duckduckgo.com/'
  16. # Create a new instance.
  17. # It is recommended to pass in a meaningful user agent.
  18. # Defaults to using the secure api (https)
  19. def initialize(http_agent_name = 'DuckDuckGo.rb', secure = true)
  20. if secure
  21. @url = API_URL_SECURE
  22. else
  23. @url = API_URL
  24. end
  25. @http = HTTPClient.new(:agent_name => http_agent_name)
  26. end
  27. # Run a query against Duck Duck Go
  28. # Returns an instance of DuckDuckGo::ZeroClickInfo
  29. def zeroclickinfo(query, skip_disambiguation = false)
  30. args = {
  31. 'q' => query,
  32. 'o' => 'json'
  33. }
  34. if(skip_disambiguation)
  35. args['d'] = 1
  36. end
  37. data = @http.get_content(@url, args)
  38. # parse the JSON and return an instance
  39. # of the ZeroClickInfo class
  40. DuckDuckGo::ZeroClickInfo.by(JSON.parse(data))
  41. end
  42. # Alias for DuckDuckGo::Main.zeroclickinfo
  43. def zci(*params)
  44. self.zeroclickinfo(*params)
  45. end
  46. end
  47. end