Sha256: 947b1d2656ee96c3b6f9079ab500753dbfc8dcff143703a84818eebafd7d9130

Contents?: true

Size: 1.86 KB

Versions: 2

Compression:

Stored size: 1.86 KB

Contents

module Europeana
  module API
    ##
    # Interface to Europeana API's Search method
    class Search
      autoload :Fields, 'europeana/api/search/fields'

      include Requestable

      # Query params
      attr_accessor :params

      class << self
        ##
        # Escapes Lucene syntax special characters for use in query parameters
        #
        # @param [String] text Text to escape
        # @return [String] Escaped text
        def escape(text)
          fail ArgumentError, "Expected String, got #{text.class}" unless text.is_a?(String)
          specials = %w<\\ + - & | ! ( ) { } [ ] ^ " ~ * ? : / >
          specials.each_with_object(text.dup) do |char, unescaped|
            unescaped.gsub!(char, '\\\\' + char) # prepends *one* backslash
          end
        end
      end

      ##
      # @param [Hash] params Europeana API request parameters for Search query
      def initialize(params = {})
        @params = HashWithIndifferentAccess.new(params)
      end

      ##
      # Base URL for a Search request
      #
      # @return [URI]
      def request_url(_options = {})
        Europeana::API.url + '/search.json'
      end

      alias_method :execute, :execute_request

      ##
      # Examines the `success` and `error` fields of the response for failure
      #
      # @raise [Europeana::Errors::RequestError] if API response has
      #   `success:false`
      # @see Requestable#parse_response
      def parse_response(response, _options = {})
        super.tap do |body|
          unless body[:success]
            klass = if body.key?(:error) && body[:error] =~ /1000 search results/
                      Errors::Request::PaginationError
                    else
                      Errors::RequestError
                    end
            fail klass, (body.key?(:error) ? body[:error] : response.code)
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
europeana-api-0.5.0 lib/europeana/api/search.rb
europeana-api-0.4.3 lib/europeana/api/search.rb