Class: Microsoft::Translator::SOAP

Inherits:
Object
  • Object
show all
Defined in:
lib/ms-translator.rb

Overview

Implements a client to the Microsoft translator SOAP API

Constant Summary collapse

SOAP_ACTION =
"http://api.microsofttranslator.com/v1/soap.svc/LanguageService/Translate"
SOAP_URL =
"http://api.microsofttranslator.com/v1/soap.svc"
SOAP_NS =
"http://api.microsofttranslator.com/v1/soap.svc"
SOAP_BODY =
%{<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<m:Translate xmlns:m="http://api.microsofttranslator.com/v1/soap.svc">
<m:appId>{{APP_ID}}</m:appId>
<m:text>{{TEXT}}</m:text>
<m:from>{{LANG_FROM}}</m:from>
<m:to>{{LANG_TO}}</m:to>
</m:Translate>
</soapenv:Body>
</soapenv:Envelope>}

Class Method Summary collapse

Class Method Details

.init_class_varsObject



53
54
55
56
57
58
59
60
61
# File 'lib/ms-translator.rb', line 53

def self.init_class_vars
  return unless @request.nil? || @tanslate_uri.nil?

  @tanslate_uri = URI.parse(SOAP_URL)

  @request = Net::HTTP::Post.new(@tanslate_uri.path)
  @request.content_type = 'text/xml; charset=utf-8'
  @request['SOAPAction'] = SOAP_ACTION
end

.translate(content, from, to) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ms-translator.rb', line 35

def self.translate(content, from, to)
  init_class_vars

  raise "Application id not set! Use `Microsoft::Translator.set_app_id(my_app_id)` to set it." unless Microsoft::Translator.const_defined?('APP_ID')

  @request.body = SOAP_BODY.sub('{{TEXT}}', content).
    sub('{{APP_ID}}', Microsoft::Translator::APP_ID).
    sub('{{LANG_FROM}}', from).sub('{{LANG_TO}}', to)

  response = Net::HTTP.new(@tanslate_uri.host, @tanslate_uri.port).start do |http|
    http.request(@request)
  end

  doc = Nokogiri::XML(response.body)

  doc.xpath('.//mst:TranslateResult/text()', 'mst' => SOAP_NS).to_s
end