Class: Nele::MsTranslator

Inherits:
GenericTranslator show all
Defined in:
lib/nele/ms_translator.rb

Instance Attribute Summary

Attributes inherited from GenericTranslator

#config, #uri

Instance Method Summary collapse

Methods inherited from GenericTranslator

build_translator_class_name, check_inheritance, #initialize, #name, #parse_uri, #translate

Constructor Details

This class inherits a constructor from Nele::GenericTranslator

Instance Method Details

#build_request(str) ⇒ Object



5
6
7
# File 'lib/nele/ms_translator.rb', line 5

def build_request(str)
  @uri = parse_uri(build_uri(str))
end

#build_uri(str) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/nele/ms_translator.rb', line 9

def build_uri(str)
  config[:url] +
    "?appId=" + config[:appId] +
    "&text=" + str +
    "&from=" + config[:from] +
    "&to=" + config[:to]
end

#connectObject



17
18
19
20
21
22
23
24
25
26
# File 'lib/nele/ms_translator.rb', line 17

def connect
  begin
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = false
    request = Net::HTTP::Get.new(uri.request_uri)
    http.request(request).body
  rescue => err
    raise Nele::ConnectionError, err
  end
end

#parse_response(res) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/nele/ms_translator.rb', line 28

def parse_response(res)
  doc = REXML::Document.new(res)
  unless doc.elements['string']
    error_message = nil
    doc.elements.each("//p") do |e|
      str = e[0].to_s
      if str.index(":")
        k,v = str.split(":")
        raise TranslatorAPIError, v.strip if k == "Message"
      end
    end
  else
    doc.elements['string'][0].to_s
  end
end