class StackMob::Client

Constants

VALID_METHODS

Attributes

app_name[RW]
app_vsn[RW]

Public Class Methods

new(base_url, app_name, app_vsn, oauth_key, oauth_secret) click to toggle source
# File lib/stackmob/client.rb, line 29
def initialize(base_url, app_name, app_vsn, oauth_key, oauth_secret)
  self.app_name = app_name
  self.app_vsn = app_vsn

  create_oauth_client(oauth_key, oauth_secret, base_url)
end

Public Instance Methods

request(method, service, path, params = {}, raw = false, headers = {}) click to toggle source
# File lib/stackmob/client.rb, line 36
def request(method, service, path, params = {}, raw = false, headers = {})
  request_path, request_body = generate_path_and_body(method, service, path, params, raw)

  args = [method, request_path]
  if [:post, :put].include?(method)
    headers.merge!("Content-Type" => "application/json") 
    args << request_body << headers
  else
    args << headers
  end

  response = @oauth_client.send(*args)

  if raw
    response
  else
    rcode = response.code.to_i
    if rcode >= 200 && rcode <= 299
      parse_response(response) if method != :delete
    else
      raise RequestError.new("\nReq Method: #{method}\nReq. Path: #{request_path}\nReq. Body: #{request_body}\nResp. Code: #{rcode}, Resp Body: #{response.respond_to?(:body) ? response.body : 'unknown'}")
    end
  end
end

Private Instance Methods

create_oauth_client(key, secret, url) click to toggle source
# File lib/stackmob/client.rb, line 61
def create_oauth_client(key, secret, url)
  @oauth_client = OAuth::AccessToken.new(OAuth::Consumer.new(key, secret, :site => url))
end
full_path(service, requested_path) click to toggle source
# File lib/stackmob/client.rb, line 91
def full_path(service, requested_path)
  "/#{service}/#{self.app_vsn}/#{self.app_name}/#{strip_prepending_slash(requested_path)}"
end
generate_path_and_body(method, service, path, params, raw) click to toggle source
# File lib/stackmob/client.rb, line 66
def generate_path_and_body(method, service, path, params, raw)
  intermediate_path = full_path(service, path)
  case method
  when :get, :delete
    [intermediate_path + "?" + (raw ? params : params_to_qs(params)), ""]
  when :post, :put
    [intermediate_path, raw ? params : Yajl::Encoder.encode(params)]
  else
    raise InvalidRequestMethod
  end
end
params_to_qs(params) click to toggle source
# File lib/stackmob/client.rb, line 79
def params_to_qs(params)
  params.to_a.map { |pair| pair.join("=") }.join("&")
end
parse_response(r) click to toggle source
# File lib/stackmob/client.rb, line 84
def parse_response(r)
  Yajl::Parser.parse(r.body)
rescue Yajl::ParseError
  raise BadResponseBody.new("#{r.body} is not valid JSON")
end
strip_prepending_slash(path) click to toggle source
# File lib/stackmob/client.rb, line 96
def strip_prepending_slash(path)
  path.gsub(/^\//, "")
end