class SocialPlus::WebApi::Client

A class which wraps calls to Social Plus Web API

Constants

API_KEY_RE
SOCIAL_PLUS_FQDN
USER_AGENT

Public Class Methods

new(api_key) click to toggle source

@param [String] api_key A Social Plus API key @raise [ArgumentError] when `api_key` is invalid

# File lib/social_plus/web_api/client.rb, line 23
def initialize(api_key)
  raise ArgumentError, 'invalid API key' unless API_KEY_RE =~ api_key
  @api_key = api_key.freeze
  freeze
end

Public Instance Methods

execute(method, parameters={}) click to toggle source

Executes a Social Plus Web API

@param [String, Symbol] method An API method name @param [Hash] parameters Parameters to API except `key` @option parameters [Symbol] :via HTTP method(default `:get`) @return [Hash] a Hash generated by parsing the JSON returned from the API call, except `status`,

just `{}` on parsing failure

@raise [ApiError] when the API returns a status other than 200 OK

# File lib/social_plus/web_api/client.rb, line 37
def execute(method, parameters={})
  parameters = parameters.with_indifferent_access
  http_method = parameters.delete(:via) || :get
  response = request(http_method, method, parameters.merge(key: @api_key))
  result = parse_as_json(response.body)

  ApiError.exception_from_api_result(response, result) unless response.is_a?(Net::HTTPOK)

  result.except('status')
end

Private Instance Methods

create_get_request(path, parameters) click to toggle source
# File lib/social_plus/web_api/client.rb, line 63
def create_get_request(path, parameters)
  Net::HTTP::Get.new(path + '?' + parameters.to_query, 'User-Agent' => USER_AGENT)
end
create_post_request(path, parameters) click to toggle source
# File lib/social_plus/web_api/client.rb, line 67
def create_post_request(path, parameters)
  Net::HTTP::Post.new(path, 'User-Agent' => USER_AGENT).tap { |request| request.body = parameters.to_query }
end
parse_as_json(json_text) click to toggle source
# File lib/social_plus/web_api/client.rb, line 77
def parse_as_json(json_text)
  json_text ||= '{}'
  JSON.parse(json_text)
rescue JSON::ParserError
  {}
end
request(http_method, api_method, parameters) click to toggle source
# File lib/social_plus/web_api/client.rb, line 55
def request(http_method, api_method, parameters)
  uri = request_uri(api_method)
  request = send("create_#{http_method.downcase}_request", uri.path, parameters)
  Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
    http.request(request)
  end
end
request_uri(method) click to toggle source
# File lib/social_plus/web_api/client.rb, line 71
def request_uri(method)
  SOCIAL_PLUS_FQDN.dup.tap do |uri|
    uri.path = '/api/%s' % method
  end
end