Skip to content

Instantly share code, notes, and snippets.

@kathgironpe
Forked from anonymous/path.rb
Created January 19, 2013 07:11
Show Gist options
  • Save kathgironpe/4571180 to your computer and use it in GitHub Desktop.
Save kathgironpe/4571180 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
require 'restclient'
require 'active_support/core_ext/hash'
require 'json'
require 'hashie'
class Path
attr_accessor :email
attr_accessor :password
attr_accessor :endpoint
attr_accessor :headers
DEFAULT_ENDPOINT = 'https://api.path.com'
DEFAULT_HEADERS = {}
# Create a new API
def initialize(email, password, options = {})
@email = email
@password = password
@endpoint = options.fetch(:endpoint, DEFAULT_ENDPOINT)
@headers = options.fetch(:headers, DEFAULT_HEADERS)
end
# method name, path for API, http method
"
feed /3/nux/feed
users_current /1/users/current.plist
user_settings /3/user/settings
moment_feed_home /3/moment/feed/home
moment /3/moment
moment_comments /3/moment/comments
activity /3/activity
".strip.split("\n").map {|l| l.strip.split(/\s+/)}.each do |api|
method_name, path, http_method = *api
http_method ||= 'get'
define_method(method_name) do |*args|
params, options = *args
send(http_method, path, params || {}, options || {})
end
end
alias_method :__moment, :moment
def moment(id, params = {}, options = {})
__moment_feed_home(params.merge(:id => id), options)
end
alias_method :__moment_comments, :moment_comments
def moment_comments(moment_ids, params = {}, options = {})
__moment_comments(params.merge(:moment_ids => moment_ids), options)
end
# Perform an HTTP GET request
def get(path, params = {}, options = {})
raw_response = options.delete(:raw_response)
response = request(:get, path, {
:headers => @headers.merge(:params => params)
}.merge(options))
parse_response(response, raw_response)
end
# Perform an HTTP POST request
def post(path, params = {}, options = {})
raw_response = options.delete(:raw_response)
response = request(:post, path, options)
parse_response(response, raw_response)
end
private
def request(http_method, path, options = {})
RestClient::Request.execute({
:method => http_method,
:url => @endpoint + path,
:user => @email,
:password => @password,
:headers => @headers,
:raw_response => true
}.merge(options))
end
def parse_response(response, raw_response = false)
return response if raw_response
if response.args[:url].match(/\.plist$/)
data = Hash.from_xml(response.to_s)
else
data = JSON.parse(response.to_s)
end
Hashie::Mash.new(data)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment