Class: Ottra

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = { }) ⇒ Ottra

Returns a new instance of Ottra.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/ottra.rb', line 8

def initialize(options = { })
  # Let's set up our languages. I don't like global variables, but I 
  $ottra_languages = YAML.load_file(File.expand_path(File.dirname(__FILE__)) + '/config/languages.yml')
  
  # Let's get our translators setup
  translator_classes = Dir.glob(File.expand_path(File.dirname(__FILE__)) + '/translators/*')
  translator_classes.each { |translator| require translator }
  
  # Now let's build a list of translator classes we can interact with
  @translators = translator_classes.map do |translator|
    # This is really a terrible way to do this...
    t = translator.split(/\/|\\/).last.gsub('.rb', '').gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
    Object.const_get(t)
  end
  
  # Let's find out how each of them are responding so we know which one to try first, unless we want to just get going
  options[:no_sorting] ? @translators = @translators.sort { |a, b| a.to_s <=> b.to_s } : sort_by_response_times
end

Instance Attribute Details

#languagesObject

Returns the value of attribute languages.



6
7
8
# File 'lib/ottra.rb', line 6

def languages
  @languages
end

#response_timesObject

Returns the value of attribute response_times.



6
7
8
# File 'lib/ottra.rb', line 6

def response_times
  @response_times
end

#translatorsObject

Returns the value of attribute translators.



6
7
8
# File 'lib/ottra.rb', line 6

def translators
  @translators
end

Instance Method Details

#sort_by_response_timesObject



39
40
41
42
# File 'lib/ottra.rb', line 39

def sort_by_response_times
  @response_times = @translators.inject({}) { |times, translator| times[translator.to_s] = translator.response_time; times }
  @translators = @translators.sort { |a, b| @response_times[a.to_s] <=> @response_times[b.to_s] }
end

#translate_text(text, destination, source = "en") ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ottra.rb', line 27

def translate_text(text, destination, source="en")
  result = text
  
  @translators.each do |translator|
    t = translator.new
    result = t.translate(text, source, destination)
    break unless text == result || (result.match(/Error: Translation from /))
  end
  
  return result
end