Skip to content

Instantly share code, notes, and snippets.

@matthutchinson
Created January 11, 2012 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthutchinson/1595355 to your computer and use it in GitHub Desktop.
Save matthutchinson/1595355 to your computer and use it in GitHub Desktop.
Ruby Google Translate v2 API wrapper and example usage
#!/usr/bin/env ruby
require 'net/http'
require 'net/https'
require 'uri'
require 'rubygems'
require 'json'
# consider these for better newline preservation?
#CGI.escape(content)
#content.gsub!(/\n/, '<br>')
#Hpricot.uxs(content)
#content.gsub('<br>', "\n")
class GoogleTranslate
BASE_URL = 'https://www.googleapis.com/language/translate/v2'
attr_accessor :key
attr_accessor :source
attr_accessor :target
def initialize(key, options = {})
@key = key
@source = options[:source]
@target = options[:target]
end
def translate(string, options = {})
uri = URI.parse(BASE_URL)
http = Net::HTTP.new(uri.host, 443)
http.use_ssl = true
response = http.request(build_request(uri, string, options))
translation_from_response(JSON.parse(response.body))
end
protected
def build_request(uri, string, options = {})
target = options[:target] || self.target
source = options[:source] || self.source
params = options.merge(:key => key, :q => string, :target => target)
params[:source] = source if source
request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(params)
request["X-HTTP-Method-Override"] = 'GET'
request
end
def translation_from_response(response)
raise "Invalid response" unless response.kind_of?(Hash)
raise "API returned error!" if response["error"]
raise "Translation data not present!" unless response["data"]
response["data"]["translations"].map { |tr| {:translation => tr["translatedText"], :detected_source => tr["detectedSourceLanguage"] }}
end
end
text_to_translate = "I stayed at the apartment with 6 colleagues, and it accommodated 7 of us with no problem at all.\r\nThe location is perfect for people visiting the Tower of London!"
translator = GoogleTranslate.new('INSERT_API_KEY_HERE')
translations = translator.translate(text_to_translate, :target => 'fr')
puts translations.first[:detected_source]
puts translations.first[:translation]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment