Class: Billomat::Search

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

Overview

This class provides the possibility to query the resources.

Instance Method Summary collapse

Constructor Details

#initialize(resource, hash) ⇒ Search

Creates a new search object.

Parameters:

  • resource (Class)

    The resource class to be queried

  • hash (Hash)

    The query


10
11
12
13
# File 'lib/billomat/search.rb', line 10

def initialize(resource, hash)
  @resource = resource
  @hash     = hash
end

Instance Method Details

#count(resp) ⇒ Integer

Returns the number of records found.

Parameters:

  • resp (Hash)

    The response from the gateway

Returns:

  • (Integer)

    the number of records found


56
57
58
59
60
# File 'lib/billomat/search.rb', line 56

def count(resp)
  return 0 if resp.nil?

  resp["#{name}s"]['@total'].to_i
end

#nameString

Returns the name of the resource.

Returns:

  • (String)

    the name of the resource


50
51
52
# File 'lib/billomat/search.rb', line 50

def name
  @resource.resource_name
end

#pathString

Returns the path including the query.

Returns:

  • (String)

    the path including the query


16
17
18
# File 'lib/billomat/search.rb', line 16

def path
  "#{@resource.base_path}?#{hash_to_query}"
end

#runArray<Billomat::Model::Base>

Runs the query and calls the gateway. Currently it will always return an empty array when no query is provided.

Returns:

  • (Array<Billomat::Model::Base>)

24
25
26
27
28
# File 'lib/billomat/search.rb', line 24

def run
  return [] if @hash.compact.empty?

  to_array(Billomat::Gateway.new(:get, path).run)
end

#to_array(resp) ⇒ Array<Billomat::Model::Base>

TODO:

Due to a strange API behaviour we have to fix the response here. This may be fixed in a new API version.

Corrects the response to always return an array.

Parameters:

  • resp (Hash)

    The response from the gateway

Returns:

  • (Array<Billomat::Model::Base>)

37
38
39
40
41
42
43
44
45
46
47
# File 'lib/billomat/search.rb', line 37

def to_array(resp)
  data = resp["#{name}s"][name]
  case data
  when Hash
    [@resource.new(data)]
  when Array
    data.map { |d| @resource.new(d) }
  else
    []
  end
end