Class: ToLang::Connector

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/to_lang/connector.rb

Overview

Responsible for making the actual HTTP request to the Google Translate API.

Constant Summary collapse

API_URL =

The base URL for all requests to the Google Translate API.

"https://www.googleapis.com/language/translate/v2"
UNSORTED_QUERY_STRING_NORMALIZER =

A custom query string normalizer that does not sort arguments. This is necessary to ensure that batch translations are returned in the same order they appear in the input array.

proc do |query|
  Array(query).map do |key, value|
    if value.nil?
      key
    elsif value.is_a?(Array)
      value.map {|v| "#{key}=#{URI.encode(v.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}"}
    else
      {key => value}.to_params
    end
  end.flatten.join('&')
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ ToLang::Connector

Initializes a new ToLang::Connector and stores a Google Translate API key.



39
40
41
42
# File 'lib/to_lang/connector.rb', line 39

def initialize(key)
  @key = key
  self.class.headers "X-HTTP-Method-Override" => "GET"
end

Instance Attribute Details

#keyString (readonly)

The Google Translate API key to use when making API calls.

Returns:

  • (String)

    The Google Translate API key.



34
35
36
# File 'lib/to_lang/connector.rb', line 34

def key
  @key
end

Instance Method Details

#request(q, target, options = {}) ⇒ String, ...

Makes a request to the Google Translate API.

Parameters:

  • q (String, Array)

    A string or array of strings to translate.

  • target (String)

    The language code for the language to translate to.

  • options (Hash) (defaults to: {})

    A hash of options.

Options Hash (options):

  • :from (String)

    The language code for the language of q.

  • :debug (Symbol)

    Debug output to return instead of the translated string. Must be one of :request, :response, or :all.

Returns:

  • (String, Array, Hash)

    The translated string, an array of the translated strings, or debugging output, as requested.

Raises:

  • (RuntimeError)

    If Google Translate returns any errors.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/to_lang/connector.rb', line 55

def request(q, target, options = {})
  request_hash = { :key => @key, :q => q, :target => target }
  request_hash[:source] = options[:from] if options[:from]
  return request_hash if options[:debug] == :request

  response = self.class.post(API_URL, { :body => request_hash })
  return response.parsed_response if options[:debug] == :response
  return { :request => request_hash, :response => response.parsed_response } if options[:debug] == :all

  raise response.parsed_response["error"]["message"] if response.parsed_response["error"] && response.parsed_response["error"]["message"]

  translations = response.parsed_response["data"]["translations"]

  if translations.size > 1
    translations.map { |translation| CGI.unescapeHTML translation["translatedText"] }
  else
    CGI.unescapeHTML(translations[0]["translatedText"])
  end
end