Sha256: 4d1ff3df0fceafb197fd667208d5b12cfb8bec4a74d049bd6bcb4127258d2bea

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

require "cognitivebing/version"
require 'json'
require 'open-uri'
require 'net/http'

class CognitiveBing
  attr_accessor :account_key, :params 
  
  def initialize(account_key, params = {})
    @account_key = account_key    
    @params = params
  end
  
  
  def search(search_term, type = 'web')
    
    
    query_string = '?q='
    query_portion = URI.encode_www_form_component('\'' + search_term + '\'')
    params = "&Ocp-Apim-Subscription-Key=#{@account_key}"
    @params.each do |k,v|
      params << "&#{k.to_s}=#{v.to_s}"
      
    end
    
    web_search_url = ""
    
    if type == "videos"
      web_search_url = "https://api.cognitive.microsoft.com/bing/v5.0/videos/search"
    elsif type == "image"
      web_search_url = "https://api.cognitive.microsoft.com/bing/v5.0/images/search"
    else
      web_search_url = "https://api.cognitive.microsoft.com/bing/v5.0/search"
    end
    
    full_address = web_search_url + query_string + query_portion + params   
    puts full_address
    
    uri = URI(full_address)
    req = Net::HTTP::Get.new(uri.request_uri)
    req.add_field("Ocp-Apim-Subscription-Key", @account_key)
    

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

    body = JSON.parse(res.body, :symbolize_names => true)
        
    
    return body
  end
  
  def suggestions(search_term)
    
    
    query_string = '?q='
    query_portion = URI.encode_www_form_component( search_term )
    
    
    
    web_search_url = "https://api.cognitive.microsoft.com/bing/v5.0/suggestions"
    
    full_address = web_search_url + query_string + query_portion 
    
    uri = URI(full_address)
    req = Net::HTTP::Get.new(uri.request_uri)
    req.add_field("Ocp-Apim-Subscription-Key", @account_key)
    

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

    body = JSON.parse(res.body, :symbolize_names => true)
        
    
    return body
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cognitivebing-0.2.0 lib/cognitivebing.rb