Class: I18nize::Translator

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

Overview

Translator for i18nize

Constant Summary collapse

ENDPOINT =
ENV.fetch("DEEPL_ENDPOINT", "https://api-free.deepl.com/v2/translate")
PLACEHOLDER_RE =
/%{\s*[^}]+\s*}/

Instance Method Summary collapse

Constructor Details

#initialize(auth_key:, from_lang: "EN", to_lang:) ⇒ Translator

Returns a new instance of Translator.



12
13
14
15
16
# File 'lib/i18nize/translator.rb', line 12

def initialize(auth_key:, from_lang: "EN", to_lang:)
  @auth_key = auth_key
  @from_lang = from_lang
  @to_lang = to_lang
end

Instance Method Details

#translate_texts(texts) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/i18nize/translator.rb', line 18

def translate_texts(texts)
  return [] if texts.empty?

  placeholders = []
  protected = texts.map do |t|
    t.to_s.gsub(PLACEHOLDER_RE) do |m|
      idx = placeholders.size
      placeholders << m
      "__I18NIZE_PLH_#{idx}__"
    end
  end

  uri = URI(ENDPOINT)
  body_params = [
    ["auth_key", @auth_key],
    ["source_lang", @from_lang],
    ["target_lang", @to_lang]
  ] + protected.map { |text| ["text", text] }

  req = Net::HTTP::Post.new(uri)
  req["Content-Type"] = "application/x-www-form-urlencoded"
  req.body = URI.encode_www_form(body_params)

  res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |h| h.request(req) }
  raise "DeepL API Error: #{res.code} - #{res.body}" unless res.is_a?(Net::HTTPSuccess)

  json = JSON.parse(res.body)
  out = json["translations"].map { |t| t["text"] }

  out.map { |s| s.gsub(/__I18NIZE_PLH_(\d+)__/) { placeholders[::Regexp.last_match(1).to_i] } }
end