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



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

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



63
64
65
66
# File 'lib/billomat/search.rb', line 63

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



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

def name
  @resource.resource_name
end

#pathString

Returns The path including the query.

Returns:

  • (String)

    The path including the query



20
21
22
# File 'lib/billomat/search.rb', line 20

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>)


29
30
31
32
# File 'lib/billomat/search.rb', line 29

def run
  return [] if @hash.reject { |k, v| v.nil? }.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 reponse 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>)


42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/billomat/search.rb', line 42

def to_array(resp)
  case count(resp)
  when 0
    []
  when 1
    # Necessary due to strange API behaviour
    [@resource.new(resp["#{name}s"][name])]
  else
    resp["#{name}s"][name].map do |c|
      @resource.new(c)
    end
  end
end