Class: Yandex::Translator

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/yandex/translator.rb,
lib/yandex/translator/version.rb

Constant Summary collapse

VERSION =
'0.3.3'

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key) ⇒ Translator

Returns a new instance of Translator.



40
41
42
# File 'lib/yandex/translator.rb', line 40

def initialize(api_key)
  @api_key = api_key
end

Class Attribute Details

.api_keyObject

Returns the value of attribute api_key.



18
19
20
# File 'lib/yandex/translator.rb', line 18

def api_key
  @api_key
end

.translatorObject (readonly)

Returns the value of attribute translator.



18
19
20
# File 'lib/yandex/translator.rb', line 18

def translator
  @translator
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



15
16
17
# File 'lib/yandex/translator.rb', line 15

def api_key
  @api_key
end

Class Method Details

.detect(text) ⇒ Object



33
34
35
# File 'lib/yandex/translator.rb', line 33

def detect(text)
  translator.detect(text)
end

.get_langsObject



25
26
27
# File 'lib/yandex/translator.rb', line 25

def get_langs
  translator.get_langs
end

.translate(text, from: nil, to: nil) ⇒ Object



29
30
31
# File 'lib/yandex/translator.rb', line 29

def translate(text, from: nil, to: nil)
  translator.translate(text, from: from, to: to)
end

Instance Method Details

#detect(text) ⇒ Object



49
50
51
52
# File 'lib/yandex/translator.rb', line 49

def detect(text)
  lang = visit('/detect', text: text)['lang']
  lang == '' ? nil : lang
end

#langsObject Also known as: get_langs



44
45
46
# File 'lib/yandex/translator.rb', line 44

def langs
  @langs ||= visit('/getLangs')['dirs']
end

#translate(text, from: nil, to: nil, format: 'plain') ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/yandex/translator.rb', line 54

def translate(text, from: nil, to: nil, format: 'plain')
  lang = (to.nil? && from.nil?) ? [] : [to, from].compact

  options = { text: text, lang: lang.reverse.join('-'), format: format }

  result = visit('/translate', options)['text']

  result.size == 1 ? result.first : result
end

#visit(address, options = {}) ⇒ Object



64
65
66
67
68
# File 'lib/yandex/translator.rb', line 64

def visit(address, options = {})
  response = self.class.post address, body: options.merge(key: api_key)
  check_errors(response)
  response
end