Module: RSimperium::ApiHelpers

Included in:
Auth, Bucket
Defined in:
lib/r_simperium/api_helpers.rb

Instance Method Summary collapse

Instance Method Details

#api_auth_headerObject



8
9
10
11
12
13
14
15
16
# File 'lib/r_simperium/api_helpers.rb', line 8

def api_auth_header
  if @host == 'auth.simperium.com'
    {'X-Simperium-API-Key' => "#{@api_key}"}
  elsif @host == 'api.simperium.com'
    {'X-Simperium-Token' => "#{@auth_token}"}
  else
    {}
  end
end

#api_meta(headers) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/r_simperium/api_helpers.rb', line 51

def api_meta(headers)
  meta = {}
  headers.each {|k,v|
    new_key = RSimperium::META_MAP[k]
    next if new_key.nil?
    if v =~ /^[-+]?[0-9]+$/
      meta[new_key] = v.to_i
    else
      meta[new_key] = v
    end
  }
  OpenStruct.new(meta)
end

#api_request(method, url, options = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/r_simperium/api_helpers.rb', line 18

def api_request(method, url, options={})
  RSimperium.log "> Api Request: #{method.to_s.upcase} #{url}"
  RSimperium.log "      Options: #{options}"
  request = options.merge(:method => method, :url => url)
  request[:headers] ||= {}
  request[:headers][:accept] ||= :json

  request[:timeout] = -1 if options[:timeout] == false

  if request[:params]
    request[:params].each do |k,v|
      request[:params][k] = '1' if v == true
    end
    # RestClient is weird, it wants the params in the headers hash
    request[:headers][:params] = request[:params]
  end

  response = RestClient::Request.execute request
  RSimperium.log ">> Response: #{response}\n\n"
  begin
    parsed = (response && response.length >= 2) ? MultiJson.decode(response) : response
    Struct::ApiResponse.new(api_meta(response.headers), parsed, response)
  rescue JSON::ParserError
    Struct::ApiResponse.new(api_meta(response.headers), response.to_s, response)
  end
end

#api_request_with_auth(method, url, options = {}) ⇒ Object



45
46
47
48
49
# File 'lib/r_simperium/api_helpers.rb', line 45

def api_request_with_auth(method, url, options={})
  options[:headers] ||= {}
  options[:headers].merge! api_auth_header
  api_request(method, url, options)
end

#api_url(path) ⇒ Object



4
5
6
# File 'lib/r_simperium/api_helpers.rb', line 4

def api_url(path)
  "#{@scheme}://#{@host}/1/#{@app_id}#{path}"
end