Class: Natsukantou::Minhon

Inherits:
Object
  • Object
show all
Includes:
UtilityBase
Defined in:
lib/natsukantou/minhon.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logger

#logger

Methods included from ParseXml

#dom, #dom_node

Constructor Details

#initialize(app, name:, key:, secret:, url:, request_params: {}, translate_by_section: nil) ⇒ Minhon

Returns a new instance of Minhon.

Parameters:

  • app (Hash)
  • name (String)

    login ID

  • key (String)

    API Key

  • secret (String)

    authentication secret

  • url (String)

    request URL of translator API endpoint

  • request_params (Hash) (defaults to: {})

    other optional request parameters

  • translate_by_section (String) (defaults to: nil)

    CSS selector to translate matched elements one by one. Minhon often returns invalid XML if xml is large. To bypass this limitation, one can specify a css path (e.g. “body>p”) to translate in smaller chunks.



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/natsukantou/minhon.rb', line 24

def initialize(
  app, name:, key:, secret:, url:, request_params: {},
  translate_by_section: nil
)
  @app = app
  @key = key
  @secret = secret
  @url = url
  @request_params = request_params.merge(name: name, key: key)

  ### Non request related setting
  @translate_by_section = translate_by_section
end

Instance Attribute Details

#envObject (readonly)

Returns the value of attribute env.



38
39
40
# File 'lib/natsukantou/minhon.rb', line 38

def env
  @env
end

#keyObject (readonly)

Returns the value of attribute key.



39
40
41
# File 'lib/natsukantou/minhon.rb', line 39

def key
  @key
end

#request_paramsObject (readonly)

Returns the value of attribute request_params.



38
39
40
# File 'lib/natsukantou/minhon.rb', line 38

def request_params
  @request_params
end

#secretObject (readonly)

Returns the value of attribute secret.



39
40
41
# File 'lib/natsukantou/minhon.rb', line 39

def secret
  @secret
end

#translate_by_sectionObject (readonly)

Returns the value of attribute translate_by_section.



40
41
42
# File 'lib/natsukantou/minhon.rb', line 40

def translate_by_section
  @translate_by_section
end

#urlObject (readonly)

Returns the value of attribute url.



39
40
41
# File 'lib/natsukantou/minhon.rb', line 39

def url
  @url
end

Instance Method Details

#call(env) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/natsukantou/minhon.rb', line 42

def call(env)
  @env = env

  if translate_by_section
    env[:dom].css(translate_by_section).each do |node|
      next if node.text.empty?

      translated_xml = translate(node.to_xml)
      node.replace(dom_node(translated_xml))
    end
  else
    translated_xml = translate(env[:dom].to_xml)
    env[:dom] = dom(translated_xml)
  end

  env[:dom].lang = env[:lang_to].code

  @app.call(env)
end