class Smartdict::Translator::LanguageDetector

It’s a translator middleware which tries to identify a language of the passed word basing on :from_lang and :to_lang options. If it’s possible to explicitly identify a language and :from_lang and :to_lang options are required to be exchanged it exchanges them.

Example:

detector = LanguageDetector.new(translator)
detector.call("groß", :from_lang => :en, :to_lang => :de)
# It delegates call to translator like this:
#   translator.call("groß", :from_lang => :de, :to_lang => :en)
# Because in English there is no character "ß" but it exists in German.

NOTE: It doesn’t support Ruby 1.8

Constants

CHARS

Public Class Methods

new(translator) click to toggle source
# File lib/smartdict/translator/language_detector.rb, line 28
def initialize(translator)
  @translator = translator

  @matchers = {}
  CHARS.each do |lang, chars|
    @matchers[lang] = Matcher.new(chars)
  end
end

Public Instance Methods

call(word, opts) click to toggle source
# File lib/smartdict/translator/language_detector.rb, line 37
def call(word, opts)
  if exchange?(word, opts[:from_lang], opts[:to_lang]) && !ruby18?
    opts[:to_lang], opts[:from_lang] = opts[:from_lang], opts[:to_lang]
  end
  @translator.call(word, opts)
end

Private Instance Methods

exchange?(word, from_lang, to_lang) click to toggle source
# File lib/smartdict/translator/language_detector.rb, line 47
def exchange?(word, from_lang, to_lang)
  from_matcher = @matchers[from_lang.to_sym]
  to_matcher   = @matchers[to_lang.to_sym]
  return false unless [from_matcher, to_matcher].all?
  to_matcher.match?(word) && !from_matcher.match?(word)
end
ruby18?() click to toggle source
# File lib/smartdict/translator/language_detector.rb, line 54
def ruby18?
  RUBY_VERSION =~ /^1\.8/
end