Module: Babel

Defined in:
lib/rbabel/translation.rb

Class Method Summary collapse

Class Method Details

.fetch_translation(text, source_lang, dest_lang) ⇒ Object

Fetches the translation page from Google.



12
13
14
15
16
17
18
19
20
21
# File 'lib/rbabel/translation.rb', line 12

def self.fetch_translation(text, source_lang, dest_lang)
  res = Net::HTTP.start('google.com', 80) do |h|
    h.get("/translate_t?langpair=%s|%s&text=%s" % [
      source_lang,
      dest_lang,
      uri_escape(text)
    ])
  end
  res.body
end

.translate(text, source_lang, *dest_lang) ⇒ Object

Translates the given text from the given source language into one or more destination languages.



25
26
27
28
29
30
31
# File 'lib/rbabel/translation.rb', line 25

def self.translate(text, source_lang, *dest_lang)
  translations = dest_lang.map do |l|
    doc = Hpricot(fetch_translation(text, source_lang, l))
    (doc/"#result_box").text
  end
  (dest_lang.size == 1) ? translations.first : translations
end

.uri_escape(text) ⇒ Object

Encodes a string into a URI-escaped string.



6
7
8
9
# File 'lib/rbabel/translation.rb', line 6

def self.uri_escape(text)
  text.gsub(/([^ a-zA-Z0-9_.-]+)/n) {'%'+$1.unpack('H2'*$1.size).
    join('%').upcase}.tr(' ', '+')
end