File: cache.rb

package info (click to toggle)
ruby-fast-gettext 4.1.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 676 kB
  • sloc: ruby: 3,209; makefile: 4
file content (44 lines) | stat: -rw-r--r-- 1,044 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
# frozen_string_literal: true

module FastGettext
  class Cache
    def initialize
      @store = {}
      reload!
    end

    def fetch(key)
      translation = @current[key]
      if translation.nil? # uncached
        @current[key] = yield || false # TODO: get rid of this false hack and cache :missing
      else
        translation
      end
    end

    # TODO: only used for tests, maybe if-else around it ...
    def []=(key, value)
      @current[key] = value
    end

    # key performance gain:
    # - no need to lookup locale on each translation
    # - no need to lookup text_domain on each translation
    # - super-simple hash lookup
    def switch_to(text_domain, locale)
      @store[text_domain] ||= {}
      @store[text_domain][locale] ||= {}
      @store[text_domain][locale][""] = false # ignore gettext meta key when translating
      @current = @store[text_domain][locale]
    end

    def delete(key)
      @current.delete(key)
    end

    def reload!
      @current = {}
      @current[""] = false
    end
  end
end