Class: TranslationDiff::SentenceCache
- Inherits:
-
Object
- Object
- TranslationDiff::SentenceCache
- Defined in:
- lib/translation_diff/sentence_cache.rb
Overview
Reads and writes sentence translations under the pipeline's cache key format, without touching the caller's array.
Defined Under Namespace
Classes: Error
Constant Summary collapse
- SCALARS =
The value types the key format can render. An allowlist: what it cannot render must raise, not be guessed at.
[String, Symbol, Numeric, TrueClass, FalseClass, NilClass].freeze
Instance Method Summary collapse
-
#fill(segments) ⇒ Object
Sets a translation on every segment the store already has cached, and hands back the rest as a new array.
-
#initialize(store:, provider:, from:, to:, options: {}) ⇒ SentenceCache
constructor
A new instance of SentenceCache.
-
#key(segment) ⇒ Object
provider:from:to:sentence, with a digest of the per-call options wedged in as a field of its own when there are any.
-
#store(segments) ⇒ Object
Writes back only the segments that carry a translation; an untranslated segment has nothing worth caching.
Constructor Details
#initialize(store:, provider:, from:, to:, options: {}) ⇒ SentenceCache
Returns a new instance of SentenceCache.
9 10 11 12 13 14 15 |
# File 'lib/translation_diff/sentence_cache.rb', line 9 def initialize(store:, provider:, from:, to:, options: {}) @store = store @provider = provider @from = from.downcase @to = to.downcase @options = end |
Instance Method Details
#fill(segments) ⇒ Object
Sets a translation on every segment the store already has cached, and hands back the rest as a new array.
23 24 25 26 27 28 29 30 31 |
# File 'lib/translation_diff/sentence_cache.rb', line 23 def fill(segments) values = @store.read_multi(segments.map { |segment| key(segment) }) misses = [] segments.each_with_index do |segment, index| value = values[index] value.nil? ? misses << segment : segment.translation = value end misses end |
#key(segment) ⇒ Object
provider:from:to:sentence, with a digest of the per-call options wedged in as a field of its own when there are any.
18 19 20 |
# File 'lib/translation_diff/sentence_cache.rb', line 18 def key(segment) [@provider, @from, @to, *, Digest::MD5.hexdigest(segment.body)].join(":") end |
#store(segments) ⇒ Object
Writes back only the segments that carry a translation; an untranslated segment has nothing worth caching. A store that batches gets one call; one that does not keeps the per-key contract it was written against.
35 36 37 38 39 40 41 42 |
# File 'lib/translation_diff/sentence_cache.rb', line 35 def store(segments) translated = segments.select(&:translated?) return translated if translated.empty? return translated.each { |segment| @store.write(key(segment), segment.translation) } if legacy_store? @store.write_multi(translated.map { |segment| [key(segment), segment.translation] }) translated end |