Class: Pollex::Translator
- Inherits:
-
Object
- Object
- Pollex::Translator
- Includes:
- Singleton
- Defined in:
- lib/pollex/translator.rb
Overview
Singleton object for translating descriptions into English.
Instance Method Summary collapse
-
#initialize ⇒ Translator
constructor
Instantiates a cache of size 100 for storing translations.
-
#translate(phrase, source_lang_code, context = nil) ⇒ Object
Translates a phrase into English using the free MyMemory API, and caches the result.
Constructor Details
#initialize ⇒ Translator
Instantiates a cache of size 100 for storing translations.
7 8 9 |
# File 'lib/pollex/translator.rb', line 7 def initialize() @cache = LRUCache.new(:max_size => 2500, :default => nil) end |
Instance Method Details
#translate(phrase, source_lang_code, context = nil) ⇒ Object
Note:
MyMemory currently has a limit of 100 API requests per IP per day for unregistered users.
Translates a phrase into English using the free MyMemory API, and caches the result.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/pollex/translator.rb', line 19 def translate(phrase, source_lang_code, context = nil) context ||= [phrase] if context.all? {|x| CLD.detect_language(x)[:code] == 'en'} # we are reasonably sure that this phrase is already in English - no need to translate phrase else # first, check the cache key = [phrase, source_lang_code] if @cache[key] @cache[key] else # make a request to MyMemory puts "Translating '#{phrase}' from (#{source_lang_code}) ..." url = "http://mymemory.translated.net/api/get?q=#{URI::encode(phrase)}&langpair=#{source_lang_code}%7Cen" results_json = open(url).read result = JSON.parse(results_json)['responseData']['translatedText'] if result.include? 'MYMEMORY WARNING' # translation failed - return original phrase puts result phrase else # translation succeeded - store into cache and return translated phrase @cache[key] = result result end end end end |