Just a quick post to get share something I was tinkering with this evening.
I came across this post by Gerald Bauer, which shows you how to use the Google Translation API with Ruby via Net::HTTP. I thought I’d play with the service with HTTParty.
class GoogleApi
include HTTParty
base_uri ‘ajax.googleapis.com’
def self.translate(string=””, to=””, from=”en”)
get(“/ajax/services/language/translate”, :query => {:langpair =>
“#{from}|#{to}”, :q => string, :v => 1.0})
end
end\
A few examples from playing with it.
>> GoogleApi.translate(‘bonjour’, ‘en’, ‘fr’)
=> “{"responseData": {"translatedText":"hello"},
"responseDetails": null, "responseStatus": 200}”
>> GoogleApi.translate(‘Red wine’, ‘fr’)
=> “{"responseData": {"translatedText":"Vin
rouge","detectedSourceLanguage":"en"}, "responseDetails":
null, "responseStatus": 200}”
>> GoogleApi.translate(‘Where is the bathroom?’, ‘es’)
=> “{"responseData":
{"translatedText":"\302\277D\303\263nde est\303\241 el
ba\303\261o?","detectedSourceLanguage":"en"},
"responseDetails": null, "responseStatus": 200}”
>> GoogleApi.translate(‘Good morning’, ‘it’)
=> “{"responseData": {"translatedText":"Buon
giorno","detectedSourceLanguage":"en"}, "responseDetails":
null, "responseStatus": 200}”
What a party!
>> GoogleApi.translate(‘party’, ‘it’)
{lang=”ruby”}
=> “{\”responseData\“: {\”translatedText\“:\”festa\“,\”detectedSourceLanguage\“:\”en\“}, \”responseDetails\“: null, \”responseStatus\“: 200}”
{lang=”ruby”}
>> GoogleApi.translate(‘party’, ‘es’)
{lang=”ruby”}
=> “{\”responseData\“: {\”translatedText\“:\”fiesta\“,\”detectedSourceLanguage\“:\”en\“}, \”responseDetails\“: null, \”responseStatus\“: 200}”
{lang=”ruby”}\
Look how easy that was. :-)
For a previous post on using this gem, read The HTTParty has just begun.