Class: TranslationDiff::Translation::Response

Inherits:
Data
  • Object
show all
Defined in:
lib/translation_diff/translation/response.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#detected_source ⇒ Object (readonly)

Returns the value of attribute detected_source

Returns:

  • (Object) —

    the current value of detected_source



3
4
5
# File 'lib/translation_diff/translation/response.rb', line 3

def detected_source
  @detected_source
end

#texts ⇒ Object (readonly)

Returns the value of attribute texts

Returns:

  • (Object) —

    the current value of texts



3
4
5
# File 'lib/translation_diff/translation/response.rb', line 3

def texts
  @texts
end

#usage ⇒ Object (readonly)

Returns the value of attribute usage

Returns:

  • (Object) —

    the current value of usage



3
4
5
# File 'lib/translation_diff/translation/response.rb', line 3

def usage
  @usage
end

Class Method Details

.build(request:, texts:, detected_source: nil, usage: nil) ⇒ Object



4
5
6
7
8
9
10
11
# File 'lib/translation_diff/translation/response.rb', line 4

def self.build(request:, texts:, detected_source: nil, usage: nil)
  ensure_count!(request, texts)
  ensure_strings!(texts)

  # Every provider's text lands here, so it takes the same path @core did: escaped, then decoded once, so an
  # entity a provider genuinely sent survives as the entity it is rather than the bare character it decodes to.
  new(texts: texts.map { |text| decoded(text) }, detected_source: detected_source, usage: usage)
end

.decoded(text) ⇒ Object



13
14
15
# File 'lib/translation_diff/translation/response.rb', line 13

def self.decoded(text)
  TranslationDiff::Markup.decode_entities(TranslationDiff::Markup.escape_bare_angles(text))
end

.ensure_count!(request, texts) ⇒ Object



17
18
19
20
21
22
# File 'lib/translation_diff/translation/response.rb', line 17

def self.ensure_count!(request, texts)
  return if texts.size == request.texts.size

  raise TranslationDiff::ResponseError,
        "Provider returned #{texts.size} translations for #{request.texts.size} values"
end

.ensure_strings!(texts) ⇒ Object

The class, never the value: the value is either the customer's text or the provider's own error object.



25
26
27
28
29
30
31
32
33
# File 'lib/translation_diff/translation/response.rb', line 25

def self.ensure_strings!(texts)
  index = texts.index { |text| !text.is_a?(String) }
  return if index.nil?

  raise TranslationDiff::ResponseError,
        "Provider returned #{texts[index].class} rather than a translation at position " \
        "#{index} of #{texts.size}. A response can be well-formed and still carry no " \
        "translation for one input -- a per-string failure inside a batch that answered 200."
end