File: mo_file.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 (80 lines) | stat: -rw-r--r-- 2,194 bytes parent folder | download | duplicates (2)
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
74
75
76
77
78
79
80
# frozen_string_literal: true

require 'fast_gettext/vendor/mofile'
module FastGettext
  # Responsibility:
  #  - abstract mo files for Mo Repository
  class MoFile
    PLURAL_SEPARATOR = "\000"
    CONTEXT_SEPARATOR = "\004"

    # file => path or FastGettext::GetText::MOFile
    def initialize(file, options = {})
      @filename = file
      @data = nil
      load_data if options[:eager_load]
    end

    def [](key)
      data[key]
    end

    # returns the plural forms or all singular translations that where found
    # Car, Cars => [Auto,Autos] or []
    def plural(*msgids)
      split_plurals(self[msgids * PLURAL_SEPARATOR].to_s)
    end

    def pluralisation_rule
      # gettext uses 0 as default rule, which would turn off all pluralisation, very clever...
      # additionally parsing fails when directly accessing po files, so this line was taken from gettext/mofile
      (data[''] || '').split("\n").each do |line|
        if /^Plural-Forms:\s*nplurals\s*\=\s*(\d*);\s*plural\s*\=\s*([^;]*)\n?/ =~ line
          return ->(n) do # rubocop:disable Lint/UnusedBlockArgument
            eval($2) # rubocop:disable Security/Eval
          end
        end
      end
      nil
    end

    def data
      load_data if @data.nil?
      @data
    end

    def self.empty
      @empty ||= MoFile.new(File.join(__dir__, 'vendor', 'empty.mo'), eager_load: true).freeze
    end

    private

    def load_data
      @data =
        if @filename.is_a? FastGettext::GetText::MOFile
          @filename
        else
          FastGettext::GetText::MOFile.open(@filename, "UTF-8")
        end
      make_singular_and_plural_available
    end

    # (if plural==singular, prefer singular)
    def make_singular_and_plural_available
      data = {}
      @data.each do |key, translation|
        next unless key.include? PLURAL_SEPARATOR

        singular, plural = split_plurals(key)
        translation = split_plurals(translation)
        data[singular] ||= translation[0]
        data[plural] ||= translation[1]
      end
      @data.merge!(data) { |_key, old, _new| old }
    end

    def split_plurals(singular_plural)
      singular_plural.split(PLURAL_SEPARATOR)
    end
  end
end