Class: GoogleSiteSearch::UrlBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/google-site-search/url_builder.rb

Overview

UrlBuilder is responsible for generating a valid url for querying the google search API.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(search_term, search_engine_id, params = {}) ⇒ UrlBuilder

Attributes

  • search_term - should be a simple search with no filters added.

Even though Googles search API uses filters on the search term itself, I wanted to separate out that functionality. Filters should be added separately as a param.

  • search_engine_id - your unique id found in your Google Site Search control panel.

  • params - supply a hash that is converted to query params. See Request Params.

Raises:

  • (ArgumentError)


21
22
23
24
25
26
27
28
# File 'lib/google-site-search/url_builder.rb', line 21

def initialize search_term, search_engine_id, params = {}
			raise ArgumentError if search_term.blank? || search_engine_id.blank?
  @search_term = search_term
  @search_engine_id = search_engine_id
  @custom_params = params.with_indifferent_access
			@filter = @custom_params.delete :filter
			@sort = @custom_params.delete :sort 
end

Instance Attribute Details

#custom_paramsObject

Returns the value of attribute custom_params.



6
7
8
# File 'lib/google-site-search/url_builder.rb', line 6

def custom_params
  @custom_params
end

#filterObject

Returns the value of attribute filter.



6
7
8
# File 'lib/google-site-search/url_builder.rb', line 6

def filter
  @filter
end

#search_engine_idObject

Returns the value of attribute search_engine_id.



6
7
8
# File 'lib/google-site-search/url_builder.rb', line 6

def search_engine_id
  @search_engine_id
end

#search_termObject

Returns the value of attribute search_term.



6
7
8
# File 'lib/google-site-search/url_builder.rb', line 6

def search_term
  @search_term
end

#sortObject

Returns the value of attribute sort.



6
7
8
# File 'lib/google-site-search/url_builder.rb', line 6

def sort
  @sort
end

Instance Method Details

#queryObject

Joins the search term and the filters, to get the full search query that google expects.



31
32
33
# File 'lib/google-site-search/url_builder.rb', line 31

def query
	[@search_term,@filter].compact.join(" ")
end

#urlObject Also known as: to_s

Returns a fully qualified URL for the Google search API.



36
37
38
# File 'lib/google-site-search/url_builder.rb', line 36

def url
  "#{GOOGLE_SEARCH_URL}/cse?#{@custom_params.merge(DEFAULT_PARAMS).merge(:q => query, :cx => @search_engine_id, :sort => @sort).delete_if{|k,v| v.nil?}.to_query}" 
end