Last active
August 13, 2023 20:26
-
-
Save sshaw/07f80e166dbe6d4b64b8 to your computer and use it in GitHub Desktop.
Ruby API client for the Gender API (https://gender-api.com)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
I want to change my gender what do I need to do to make it happen