Class: Perfectline::T9n::GoogleTranslator

Inherits:
Object
  • Object
show all
Defined in:
lib/t9n/util.rb

Class Method Summary collapse

Class Method Details

.translate(text, to, from = 'en') ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/t9n/util.rb', line 69

def self.translate(text, to, from='en')

  base = 'http://ajax.googleapis.com/ajax/services/language/translate'

  # assemble query params
  params = {
          :langpair => "#{from}|#{to}",
          :q => text,
          :v => 1.0
  }

  query = params.map{ |k, v| "#{k}=#{CGI.escape(v.to_s)}" }.join('&')

  # send get request
  response = Net::HTTP.get_response( URI.parse( "#{base}?#{query}" ) )
  json = JSON.parse( response.body )

  if json['responseStatus'] == 200
    json['responseData']['translatedText']
  else
    raise StandardError, response['responseDetails']
  end
end