Class: Google::Translator

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

Constant Summary collapse

URL_STRING =
"http://ajax.googleapis.com/ajax/services/language/"
URL2_STRING =
"http://translate.google.com"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.Exception(*names) ⇒ Object



15
16
17
18
# File 'lib/google_translate.rb', line 15

def self.Exception(*names)
  cl = Module === self ? self : Object
  names.each {|n| cl.const_set(n, Class.new(Exception))}
end

Instance Method Details

#detect_language(test_text) ⇒ Object

Raises:

  • (MissingTestText)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/google_translate.rb', line 48

def detect_language(test_text)
  raise(MissingTestText) if test_text.nil?

  request = URL_STRING + "detect?v=1.0&q=" + CGI.escape(test_text) 

  begin
    response = call_service(request, [:response_data]) 
    response_data = response[:response_data]

    raise(TranslateServerIsDown) if response.empty?

    response_data
  rescue OpenURI::HTTPError
    raise(TranslateServerIsDown)
  end
end

#supported_languagesObject



65
66
67
# File 'lib/google_translate.rb', line 65

def supported_languages
  call_service2(URL2_STRING , [])
end

#translate(from, to, from_text, options = {}) ⇒ Object

Raises:

  • (MissingFromLanguage)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/google_translate.rb', line 26

def translate(from, to, from_text, options={})
  raise(MissingFromLanguage) if from.nil?
  raise(MissingToLanguage) if to.nil?
  raise(MissingTextLanguage) if from_text.nil?

  request = URL_STRING + "translate?v=1.0&langpair=#{from}%7C#{to}&q=" + CGI.escape(from_text) 
  
  begin
    response = call_service(request, [:response_status, :response_details, :response_data])

    raise(TranslateServerIsDown) if response.empty?

    raise(InvalidResponse, response[:response_details]) if response[:response_status] != 200 # success

    to_text = response[:response_data]['translatedText']

    (options[:html]) ? CGI.unescapeHTML(to_text) : to_text
  rescue OpenURI::HTTPError
    raise(TranslateServerIsDown)
  end
end