lib/tr4n5l4te/translator.rb in tr4n5l4te-0.1.8 vs lib/tr4n5l4te/translator.rb in tr4n5l4te-0.1.9
- old
+ new
@@ -12,30 +12,46 @@
@sleep_time = args.fetch(:sleep_time, 2)
@agent = Agent.new
end
def translate(text, from_lang, to_lang)
- puts "Translating: #{text}"
encoded_text = validate_and_encode(text)
return '' if encoded_text == ''
smart_visit(translator_url(encoded_text, from_lang, to_lang))
result_box = browser.find('.tlid-translation')
- result_box.text
+ postprocess(result_box.text)
rescue Capybara::Ambiguous
all_translations = browser.find_all('.tlid-translation')
multiples = all_translations.collect(&:text)
puts("WARNING: '#{text}' has multiple translations: [#{multiples.join(', ')}]")
text
end
private
+ def preprocess(text)
+ @interpolations = text.scan(/(%{.*})/).flatten
+ @interpolations.each_with_index do |var, ndx|
+ stub = "VAR#{ndx}"
+ text.gsub!(%r{#{var}}, stub)
+ end
+ text
+ end
+
+ def postprocess(text)
+ @interpolations.each_with_index do |interp, ndx|
+ stub = /VAR#{ndx}/
+ text.gsub!(stub, interp)
+ end
+ text
+ end
+
def validate_and_encode(text)
return '' if text.nil?
fail "Cannot translate a [#{text.class}]: '#{text}'" unless text.respond_to?(:gsub)
- CGI.escape(text.strip)
+ CGI.escape(preprocess(text.strip))
end
def smart_visit(url)
load_cookies
agent.visit(url)