Class: Bing

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

Overview

The Bing Class provides the ability to connect to the bing search api hosted on the windows azure marketplace. Before proceeding you will need an account key, which can be obtained by registering an accout at windows.microsoft.com/en-US/windows-live/sign-in-what-is-microsoft-account

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(account_key, num_results, type) ⇒ Bing

Create a new object of the bing class

>> bing_image = Bing.new('your_account_key_goes_here', 10, 'Image') 
=> #<Bing:0x9d9b9f4 @account_key="your_account_key", @num_results=10, @type="Image">

Arguments:

account_key: (String)
num_results: (Integer)
type:      (String)


16
17
18
19
20
21
22
23
# File 'lib/searchbing.rb', line 16

def initialize(, num_results, type)

  @account_key = 
  @num_results = num_results
  @type = type


end

Instance Attribute Details

#account_keyObject

Returns the value of attribute account_key.



25
26
27
# File 'lib/searchbing.rb', line 25

def 
  @account_key
end

#num_resultsObject

Returns the value of attribute num_results.



25
26
27
# File 'lib/searchbing.rb', line 25

def num_results
  @num_results
end

#typeObject

Returns the value of attribute type.



25
26
27
# File 'lib/searchbing.rb', line 25

def type
  @type
end

Instance Method Details

#search(search_term, offset = 0) ⇒ Object

Search for a term, the result is an array of hashes with the result data

>> bing_image.search("puffin") 
=> [{"__metadata"=>{"uri"=>"https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query='puffin'&$skip=0&$top=1", "type"=>"Image

Arguments:

search_term: (String)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/searchbing.rb', line 33

def search(search_term, offset = 0)
   
  user = ''
  web_search_url = "https://api.datamarket.azure.com/Bing/Search/#{type}?$format=json&Query="
  query_portion = URI.encode_www_form_component('\'' + search_term + '\'')
  params = "&$top=#{@num_results}&$skip=#{offset}"
  full_address = web_search_url + query_portion + params

  uri = URI(full_address)
  req = Net::HTTP::Get.new(uri.request_uri)
  req.basic_auth user, 

  res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https'){|http|
      http.request(req)
  }

  body = JSON.parse(res.body)
  result_set = body["d"]["results"]  
end