Read my latest article: Lessons in Open Source (posted Mon, 27 Jun 2016 17:04:00 GMT)

HTTParty goes foreign

Posted by Mon, 16 Mar 2009 07:05:00 GMT

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')
=> "{\"responseData\": {\"translatedText\":\"festa\",\"detectedSourceLanguage\":\"en\"}, \"responseDetails\": null, \"responseStatus\": 200}"
>> GoogleApi.translate('party', 'es')
=> "{\"responseData\": {\"translatedText\":\"fiesta\",\"detectedSourceLanguage\":\"en\"}, \"responseDetails\": null, \"responseStatus\": 200}"

Look how easy that was. :-)

For a previous post on using this gem, read The HTTParty has just begun.

Get help with your Rails project

comments powered by Disqus