class Smartdict::Drivers::GoogleTranslateDriver

The translation driver for Google Translate service.

Constants

HOST

Host of Google Translate service.

USER_AGENT

Pretend being Firefox :)

Public Instance Methods

translate() click to toggle source

Sets translation and transcription. GoogleTranslate doesn’t provide transcription, so it’s nil.

# File lib/smartdict/drivers/google_translate_driver.rb, line 15
def translate
  self.translated = response_to_hash(get_response)
  self.transcription = nil
end

Private Instance Methods

get_response() click to toggle source

Sends remote request to GooogleTranslate service. @return [String] body of response.

# File lib/smartdict/drivers/google_translate_driver.rb, line 43
def get_response
  http = Net::HTTP.new(HOST, 80)
  request = Net::HTTP::Get.new(http_path, {"User-Agent" => USER_AGENT})
  http.request(request).read_body
end
http_path() click to toggle source

@return [String] http path for request to translate word.

# File lib/smartdict/drivers/google_translate_driver.rb, line 50
def http_path
  w = word.gsub(' ', '+')
  "/translate_a/t?client=t&text=#{w}&hl=en&sl=#{from_lang}&tl=#{to_lang}&multires=1&otf=1&rom=1&ssel=0&tsel=0&sc=1"
end
response_to_hash(response) click to toggle source

Parses string return by GoogleTranslate Returns hash similar to this:

{ "noun" => ["try", "attempt"],
  "verb" => ["try", "offer"] }

If no translation was found than returns nil. @return [Hash] every key is word class and every value is array of translated words.

# File lib/smartdict/drivers/google_translate_driver.rb, line 29
def response_to_hash(response)
  result = {}
  array = YAML.load(response.gsub(/,+/, ', '))
  array[1].each do |trans|
    word_class = trans[0].empty? ? 'undefined' : trans[0]
    result[word_class] = trans[1]
  end
  result
rescue NoMethodError
  raise Smartdict::TranslationNotFound
end