Class: GoogleLanguage

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

Class Method Summary collapse

Class Method Details

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



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/google_language.rb', line 8

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