Class: Tr4n5l4te::Translator

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

Constant Summary collapse

START_PAGE =
'https://translate.google.com'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ Translator

Returns a new instance of Translator.



11
12
13
14
# File 'lib/tr4n5l4te/translator.rb', line 11

def initialize(args = {})
  @sleep_time = args.fetch(:sleep_time, 2)
  @agent = Agent.new
end

Instance Attribute Details

#agentObject (readonly)

Returns the value of attribute agent.



9
10
11
# File 'lib/tr4n5l4te/translator.rb', line 9

def agent
  @agent
end

#sleep_timeObject (readonly)

Returns the value of attribute sleep_time.



9
10
11
# File 'lib/tr4n5l4te/translator.rb', line 9

def sleep_time
  @sleep_time
end

Instance Method Details

#translate(text, from_lang, to_lang) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tr4n5l4te/translator.rb', line 16

def translate(text, from_lang, to_lang)
  encoded_text = validate_and_encode(text)
  return '' if encoded_text == ''

  smart_visit(translator_url(encoded_text, from_lang, to_lang))
  result_box = browser.find('.JLqJ4b.ChMk0b > span:first-child')
  postprocess(result_box.text)

rescue Capybara::Ambiguous
  all_translations = browser.find_all('.JLqJ4b.ChMk0b > span:first-child')
  multiples = all_translations.collect(&:text)
  puts("WARNING: '#{text}' has multiple translations: [#{multiples.join(', ')}]")
  text

rescue Capybara::ElementNotFound
  all_translations = browser.find_all('.J0lOec > span:first-child')
  multiples = all_translations.collect(&:text)
  if multiples.any?
    puts("WARNING: '#{text}' has gender translations: [#{multiples.join(', ')}]")
    postprocess(multiples.last) # take the male form
  else
    puts("WARNING: Could not find a translation for '#{text}'")
  end
end