29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/wordref.rb', line 29
def translate(params = {})
if !accepted_langs.keys.include?(params[:from] + params[:to])
raise InvalidLangFormat,
"Invalid chosen language (#{params[:from]} / #{params[:to]}).\n" +
"Accepted langs are:\n" + accepted_langs.to_s
end
dic = "#{params[:from] || 'en'}#{params[:to]}"
word = params[:word]
response = attempt(3, 3) {
open("http://www.wordreference.com/#{dic}/#{URI::encode(word)}",
'User-Agent' => 'Mozilla/5.0 (X11; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0').read
}
doc = Nokogiri::HTML(response)
first_trans = doc.css("tr[id^='#{dic}:']").first
return nil if first_trans.nil?
first_trans.css('td[class="ToWrd"] > text()').to_s.strip
end
|