Class: ToLang::Connector
- Inherits:
-
Object
- Object
- ToLang::Connector
- 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
-
#key ⇒ String
readonly
The Google Translate API key to use when making API calls.
Instance Method Summary collapse
-
#initialize(key) ⇒ ToLang::Connector
constructor
Initializes a new Connector and stores a Google Translate API key.
-
#request(q, target, options = {}) ⇒ String, ...
Makes a request to the Google Translate API.
Constructor Details
#initialize(key) ⇒ ToLang::Connector
Initializes a new ToLang::Connector and stores a Google Translate API key.
38 39 40 41 |
# File 'lib/to_lang/connector.rb', line 38 def initialize(key) @key = key self.class.headers "X-HTTP-Method-Override" => "GET" end |
Instance Attribute Details
#key ⇒ String (readonly)
The Google Translate API key to use when making API calls.
33 34 35 |
# File 'lib/to_lang/connector.rb', line 33 def key @key end |
Instance Method Details
#request(q, target, options = {}) ⇒ String, ...
Makes a request to the Google Translate API.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/to_lang/connector.rb', line 54 def request(q, target, = {}) request_hash = { :key => @key, :q => q, :target => target } request_hash[:source] = [:from] if [:from] return request_hash if [:debug] == :request response = self.class.post(API_URL, { :body => request_hash }) return response.parsed_response if [:debug] == :response return { :request => request_hash, :response => response.parsed_response } if [: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 |