File: merge.rb

package info (click to toggle)
ruby-fast-gettext 1.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 720 kB
  • ctags: 301
  • sloc: ruby: 3,092; makefile: 3
file content (73 lines) | stat: -rw-r--r-- 1,606 bytes parent folder | download
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
require 'fast_gettext/translation_repository/po'

module FastGettext
  module TranslationRepository
    # Responsibility:
    #  - merge data from multiple repositories into one hash structure
    #  - can be used instead of searching for translations in multiple domains
    #  - requires reload when current locale is changed
    class Merge < Base
      def initialize(name, options={})
        clear
        super(name, options)
        options.fetch(:chain, []).each do |repo|
          add_repo(repo)
        end
      end

      def available_locales
        @repositories.flat_map(&:available_locales).uniq
      end

      def pluralisation_rule
        @repositories.each do |r|
          result = r.pluralisation_rule and return result
        end
        nil
      end

      def plural(*keys)
        @repositories.each do |r|
          result = r.plural(*keys)
          return result unless result.compact.empty?
        end
        []
      end

      def reload
        @data = {}
        @repositories.each do |r|
          r.reload
          load_repo(r)
        end
        super
      end

      def add_repo(repo)
        raise "Unsupported repository" unless repo_supported?(repo)
        @repositories << repo
        load_repo(repo)
        true
      end

      def [](key)
        @data[key]
      end

      def clear
        @repositories = []
        @data = {}
      end

      protected

      def repo_supported?(repo)
        repo.respond_to?(:all_translations)
      end

      def load_repo(r)
        @data = r.all_translations.merge(@data)
      end
    end
  end
end