Class: Glosbe::Translate

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/glosbe.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(from, dest = 'eng') ⇒ Translate

Returns a new instance of Translate.

Raises:

  • (MissingFromLanguage)


10
11
12
13
# File 'lib/glosbe.rb', line 10

def initialize(from, dest='eng')
  raise(MissingFromLanguage) if from.nil?
  @options = { query: {from: from, dest: dest }}
end

Class Method Details

.Exception(*names) ⇒ Object



15
16
17
18
# File 'lib/glosbe.rb', line 15

def self.Exception(*names)
  cl = Module === self ? self : Object
  names.each {|n| cl.const_set(n, Class.new(Exception))}
end

Instance Method Details

#translate(phrase) ⇒ Object



23
24
25
# File 'lib/glosbe.rb', line 23

def translate(phrase)
  translate_and_definition(phrase)[:translated]
end

#translate_and_definition(phrase) ⇒ Object

Raises:

  • (MissingPhraseLanguage)


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/glosbe.rb', line 27

def translate_and_definition(phrase)
  raise(MissingPhraseLanguage) if phrase.nil?
  @options[:query][:phrase] = phrase

  response = self.class.get('/translate', @options)
  response = (response && response.parsed_response) ? response.parsed_response : nil

  raise(TranslateServerIsDown) if (!response || response.empty?)
  raise(IPBlocked) if (response['message'] && response['message'] == 'Too many queries, your IP has been blocked')

  target_definitions = []
  source_definitions = []
  translated = (response['tuc'] && response['tuc'].first && response['tuc'].first['phrase']) ? response['tuc'].first['phrase']['text'] : nil
  coder = HTMLEntities.new
  response['tuc'].each do |translation_block|
    next if translation_block['meanings'].nil? || translation_block['authors'].include?(1)
    translation_block['meanings'].each do |meaning|
      if meaning['language'] == @options[:query][:dest]
        target_definitions << coder.decode(meaning['text'])
      else
        source_definitions << coder.decode(meaning['text'])
      end
    end
  end

  {target_definitions: target_definitions, source_definitions: source_definitions, translated: translated}
end