Class: Pebblebed::GenericClient

Inherits:
AbstractClient show all
Defined in:
lib/pebblebed/clients/generic_client.rb

Instance Method Summary collapse

Methods inherited from AbstractClient

#delete, #get, #post, #put

Constructor Details

#initialize(session_key, root_url) ⇒ GenericClient

Returns a new instance of GenericClient.



5
6
7
8
9
# File 'lib/pebblebed/clients/generic_client.rb', line 5

def initialize(session_key, root_url)
  @root_url = root_url  
  @root_url = URI(@root_url) unless @root_url.is_a?(URI::HTTP)
  @session_key = session_key
end

Instance Method Details

#perform(method, url = '', params = {}, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/pebblebed/clients/generic_client.rb', line 11

def perform(method, url = '', params = {}, &block)
  begin
    result = Pebblebed::Http.send(method, service_url(url), service_params(params), &block)
    return DeepStruct.wrap(JSON.parse(result.body))
  rescue JSON::ParserError => e
    if e.message =~ /^lexical error: invalid bytes in UTF8 string/
      raise
    else
      # Treat as non-JSON
      return result.body
    end
  end
end

#service_params(params) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/pebblebed/clients/generic_client.rb', line 40

def service_params(params)
  if (key = @session_key) and (params.nil? or not params[:session])
    if params
      params = params.dup  # Make sure we don't modify it
    else
      params = {}
    end
    params['session'] = key
  end
  params
end

#service_url(url, params = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/pebblebed/clients/generic_client.rb', line 25

def service_url(url, params = nil)
  result = @root_url.dup
  result.path = result.path.sub(/\/+$/, "") + url
  if params
    result.query << '&' if result.query
    result.query ||= ''
    result.query << if params.is_a?(Hash)
      params.entries.map { |k, v| CGI.escape(k.to_s) + '=' + CGI.escape(v.to_s) }.join('&')
    else
      params
    end
  end
  result
end