Class: Europeana::Search

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

Overview

Interface to Europeana API's Search method

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Search

Returns a new instance of Search.

Parameters:

  • params (Hash) (defaults to: {})

    Europeana API request parameters for Search query

See Also:


13
14
15
# File 'lib/europeana/search.rb', line 13

def initialize(params = {})
  self.params = params
end

Instance Attribute Details

#paramsObject

Query params


7
8
9
# File 'lib/europeana/search.rb', line 7

def params
  @params
end

Instance Method Details

#executeObject

Sends the Search request to the API


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/europeana/search.rb', line 20

def execute
  uri = request_uri
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Get.new(uri.request_uri)
  retries = Europeana.max_retries
  
  begin
    response = http.request(request)
  rescue Timeout::Error, Errno::ECONNREFUSED, EOFError
    retries -= 1
    raise unless retries > 0
    sleep Europeana.retry_delay
    retry
  end
  
  json = JSON.parse(response.body)
  raise Errors::RequestError, json['error'] unless json['success']
  json
rescue JSON::ParserError
  raise Errors::ResponseError
end

#params_with_authenticationHash

Returns query params with API key added

Returns:

  • (Hash)

Raises:


47
48
49
50
# File 'lib/europeana/search.rb', line 47

def params_with_authentication
  raise Europeana::Errors::MissingAPIKeyError unless Europeana.api_key.present?
  params.merge(:wskey => Europeana.api_key).reverse_merge(:query => "")
end

#request_uriURI

Gets the URI for this Search request with parameters

Returns:

  • (URI)

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/europeana/search.rb', line 82

def request_uri
  uri = URI.parse(Europeana::URL + "/search.json")
  request_params = params_with_authentication

  if request_params[:qf].is_a?(Hash)
    qf = request_params.delete(:qf)
    uri.query = request_params.to_query
    qf.each_pair do |name, criteria|
      [ criteria ].flatten.each do |criterion|
        uri.query = uri.query + "&qf=" + CGI::escape(name.to_s) + ":" + CGI::escape(criterion)
      end
    end
  else
    uri.query = request_params.to_query
  end
  
  uri
end