class DetectLanguage::Client
Attributes
configuration[R]
Public Class Methods
new(configuration)
click to toggle source
# File lib/detect_language/client.rb, line 10 def initialize(configuration) @configuration = configuration end
Public Instance Methods
get(method, params = {})
click to toggle source
# File lib/detect_language/client.rb, line 18 def get(method, params = {}) execute(method, params, :http_method => Net::HTTP::Get) end
post(method, params = {})
click to toggle source
# File lib/detect_language/client.rb, line 14 def post(method, params = {}) execute(method, params, :http_method => Net::HTTP::Post) end
Private Instance Methods
execute(method, params, options)
click to toggle source
# File lib/detect_language/client.rb, line 24 def execute(method, params, options) http = setup_http_connection http_method = options[:http_method] request = http_method.new(request_uri(method)) if RUBY_VERSION == '1.8.7' set_form_data_18(request, params) else request.set_form_data(params) end request['Authorization'] = 'Bearer ' + configuration.api_key.to_s request['User-Agent'] = configuration.user_agent response = http.request(request) case response when Net::HTTPSuccess, Net::HTTPUnauthorized then parse_response(response.body) else raise(Error, "Failure: #{response.class}") end end
parse_response(response_body)
click to toggle source
# File lib/detect_language/client.rb, line 48 def parse_response(response_body) response = JSON.parse(response_body) if response.is_a?(Array) || response["error"].nil? response else raise(Error, response["error"]["message"]) end end
request_uri(method)
click to toggle source
# File lib/detect_language/client.rb, line 58 def request_uri(method) "/#{configuration.api_version}/#{method}" end
set_form_data_18(request, params, sep = '&')
click to toggle source
# File lib/detect_language/client.rb, line 81 def set_form_data_18(request, params, sep = '&') request.body = params.map {|k,v| if v.instance_of?(Array) v.map {|e| "#{urlencode(k.to_s)}=#{urlencode(e.to_s)}"}.join(sep) else "#{urlencode(k.to_s)}=#{urlencode(v.to_s)}" end }.join(sep) request.content_type = 'application/x-www-form-urlencoded' end
setup_http_connection()
click to toggle source
# File lib/detect_language/client.rb, line 62 def setup_http_connection http = Net::HTTP::Proxy(configuration.proxy_host, configuration.proxy_port, configuration.proxy_user, configuration.proxy_pass). new(configuration.host, configuration.port) http.read_timeout = configuration.http_read_timeout http.open_timeout = configuration.http_open_timeout if configuration.secure? http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER else http.use_ssl = false end http end
urlencode(str)
click to toggle source
# File lib/detect_language/client.rb, line 93 def urlencode(str) CGI::escape(str) end