Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby API client for the Gender API (https://gender-api.com)
Gem::Specification.new do |s|
s.name = "gender_api"
s.version = "0.0.1"
s.date = "2016-03-05"
s.summary = "API client for the Gender API"
s.description = "API client for the gender detection service Gender API: https://gender-api.com/en/api-docs"
s.authors = ["Skye Shaw"]
s.email = "skye.shaw@gmail.com"
s.files = Dir["*.rb"]
s.require_paths = ["."]
s.homepage = "https://gist.github.com/sshaw/07f80e166dbe6d4b64b8"
s.license = "MIT"
end
require "json"
require "uri"
require "net/http"
# API client for the Gender API (https://gender-api.com/en/api-docs)
# https://gist.github.com/sshaw/07f80e166dbe6d4b64b8
#
# By: Skye Shaw (https://github.com/sshaw)
# Date: 2016-03-05
class GenderAPI
ENDPOINT = "https://gender-api.com/get".freeze
class Error < StandardError
attr :errno
def initialize(message, errno = nil)
@errno = errno
super(message)
end
end
def initialize(key = nil)
@key = key
end
def name(name, options = {})
name = Array(name)
raise ArgumentError, "name required" unless name.any?
request(options.merge(:name => name.join(";")))
end
def split(name, options = {})
raise ArgumentError, "name required" unless name
request(options.merge(:split => name))
end
def email(email, options = {})
raise ArgumentError, "email required" unless email
request(options.merge(:email => email))
end
private
def request(params)
data = parse_response(send_request(params))
raise Error.new(data["errmsg"], data["errno"]) if data["errno"]
data
end
def send_request(params)
Net::HTTP.get(url(params))
rescue => e
raise Error, "request failed: #{e}"
end
def parse_response(json)
JSON.parse(json)
rescue JSON::ParserError => e
raise Error, "failed to parse JSON response: #{e}"
end
def url(params)
params[:key] = @key if @key
qs = URI.encode_www_form(params)
qs.gsub!("+", "%20")
URI(sprintf("%s?%s", ENDPOINT, qs))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment