fast_gettext 4.1.1 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c5e2843e35fbde82280e708ad953d0e2e4db2046c401f228d8f80b2c678eb149
4
- data.tar.gz: 300f5b287b2398b0706f79050eca58556c16ee54f8f8b88ab504c8f417cc8b3a
3
+ metadata.gz: 64684fc2728680b23966f9d04881ecb94fb8cc55bcbeb8957e8f2801ecfd9e83
4
+ data.tar.gz: 912394d101ac7f933f1b68f508a666f3fa0ac91c1dada28602c82c4eb81ff3bb
5
5
  SHA512:
6
- metadata.gz: 7a0c08120aa700cb08721d646e6665d2a124ec560306e5464af1b7ba8eb966225f1ae582328b56e6d74dc0354dc7d09046244a0587c6d08ad9a5845254965a1c
7
- data.tar.gz: 754482e2e9301da6aa510b7d6005074fd94c7aec9d195a29b4a5dfa97822c37cf82022ff8f4d13dabe4364982ff7e284734e51b114f1aa27e99a65b6d756bcf4
6
+ metadata.gz: fb36b5a79ca99b573cf98705689b718654f5950dd6ecdebfdbfd549056153bf40e91e1f3a8b43ec4904d86dd394abf07a136c96a8e6ea52430b2f958e69f28e8
7
+ data.tar.gz: 7c655075c247157540a8c35d51ba17e547e622dccb3cef2b761c438d9d34889fd3de3e85f21cb7df3fd33266418979c7f227c3c9d8773156d1bcd779e661ff1f
data/CHANGELOG CHANGED
@@ -1,3 +1,5 @@
1
+ 4.3.0 -- stop using eval for pluralisation rule
2
+ 4.2.0 -- cache pluralisation rule
1
3
  4.1.0 -- drop EOL rubies + add racc dependency
2
4
  4.0.0 -- Remove String#% hack that would make it not blow up when using invalid keys, can temporarily restore with `FastGettext.allow_invalid_keys!`
3
5
  3.1.0 -- Work with frozen strings
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'fast_gettext/vendor/mofile'
4
+ require 'fast_gettext/plural_expression'
4
5
  module FastGettext
5
6
  # Responsibility:
6
7
  # - abstract mo files for Mo Repository
@@ -25,17 +26,12 @@ module FastGettext
25
26
  split_plurals(self[msgids * PLURAL_SEPARATOR].to_s)
26
27
  end
27
28
 
29
+ # n_() asks for this on every call: read from the header and compiled the
30
+ # first time, then kept (nil when the file has none).
28
31
  def pluralisation_rule
29
- # gettext uses 0 as default rule, which would turn off all pluralisation, very clever...
30
- # additionally parsing fails when directly accessing po files, so this line was taken from gettext/mofile
31
- (data[''] || '').split("\n").each do |line|
32
- if /^Plural-Forms:\s*nplurals\s*\=\s*(\d*);\s*plural\s*\=\s*([^;]*)\n?/ =~ line
33
- return ->(n) do # rubocop:disable Lint/UnusedBlockArgument
34
- eval($2) # rubocop:disable Security/Eval
35
- end
36
- end
37
- end
38
- nil
32
+ return @pluralisation_rule if defined?(@pluralisation_rule)
33
+
34
+ @pluralisation_rule = read_pluralisation_rule
39
35
  end
40
36
 
41
37
  def data
@@ -44,11 +40,28 @@ module FastGettext
44
40
  end
45
41
 
46
42
  def self.empty
47
- @empty ||= MoFile.new(File.join(__dir__, 'vendor', 'empty.mo'), eager_load: true).freeze
43
+ @empty ||= begin
44
+ empty = MoFile.new(File.join(__dir__, 'vendor', 'empty.mo'), eager_load: true)
45
+ # pluralisation_rule keeps what it computed in an instance variable, which
46
+ # it can't set once the object is frozen: compute it first
47
+ empty.pluralisation_rule
48
+ empty.freeze
49
+ end
48
50
  end
49
51
 
50
52
  private
51
53
 
54
+ def read_pluralisation_rule
55
+ # gettext uses 0 as default rule, which would turn off all pluralisation, very clever...
56
+ # additionally parsing fails when directly accessing po files, so this line was taken from gettext/mofile
57
+ (data[''] || '').split("\n").each do |line|
58
+ if /^Plural-Forms:\s*nplurals\s*=\s*(\d*);\s*plural\s*=\s*([^;]*)\n?/ =~ line
59
+ return PluralExpression.compile($2)
60
+ end
61
+ end
62
+ nil
63
+ end
64
+
52
65
  def load_data
53
66
  @data =
54
67
  if @filename.is_a? FastGettext::GetText::MOFile
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FastGettext
4
+ # The plural expression of a Plural-Forms header, or the pluralisation_rule
5
+ # of a YAML locale, is arithmetic over n. Parse it here instead of evaluating
6
+ # it: a catalogue is input, and a rule in it must never run as Ruby code.
7
+ #
8
+ # The grammar is the one GNU gettext defines for the expression: decimal
9
+ # integers, the variable n, parentheses, the ternary ?:, comparison, equality,
10
+ # boolean, additive and multiplicative operators, and !, unary - and unary +.
11
+ # Anything else raises InvalidExpression.
12
+ module PluralExpression
13
+ # A rule outside the grammar. It is a SyntaxError because the evaluation
14
+ # this replaces raised SyntaxError for a rule Ruby could not parse.
15
+ class InvalidExpression < SyntaxError; end
16
+
17
+ OPERATORS = [
18
+ "||", "&&", "==", "!=", "<=", ">=", "<", ">",
19
+ "+", "-", "*", "/", "%", "!", "?", ":", "(", ")"
20
+ ].freeze
21
+ PRECEDENCE = {
22
+ "||" => 1,
23
+ "&&" => 2,
24
+ "==" => 3, "!=" => 3,
25
+ "<" => 4, "<=" => 4, ">" => 4, ">=" => 4,
26
+ "+" => 5, "-" => 5,
27
+ "*" => 6, "/" => 6, "%" => 6
28
+ }.freeze
29
+ TOKEN = /\s+|#{Regexp.union(OPERATORS)}|\d+|\bn\b|./
30
+
31
+ module_function
32
+
33
+ # Compile a rule to a callable that selects a plural index for a count.
34
+ def compile(source)
35
+ expression = Parser.new(tokenize(source)).parse
36
+ ->(n) { evaluate(expression, n) }
37
+ end
38
+
39
+ def tokenize(source)
40
+ tokens = source.to_s.scan(TOKEN)
41
+ tokens.reject! { |token| token.match?(/\A\s+\z/) }
42
+ tokens.each do |token|
43
+ next if token == "n" || token.match?(/\A\d+\z/) || OPERATORS.include?(token)
44
+
45
+ raise InvalidExpression, "unexpected #{token.inspect} in plural expression"
46
+ end
47
+ tokens
48
+ end
49
+
50
+ def evaluate(expression, n)
51
+ case expression[0]
52
+ when :number
53
+ expression[1]
54
+ when :variable
55
+ n
56
+ when :not
57
+ !evaluate(expression[1], n)
58
+ when :negate
59
+ -evaluate(expression[1], n)
60
+ when :positive
61
+ evaluate(expression[1], n)
62
+ when :conditional
63
+ evaluate(expression[1], n) ? evaluate(expression[2], n) : evaluate(expression[3], n)
64
+ else
65
+ operator = expression[1]
66
+ left = evaluate(expression[2], n)
67
+ return left && evaluate(expression[3], n) if operator == "&&"
68
+ return left || evaluate(expression[3], n) if operator == "||"
69
+
70
+ right = evaluate(expression[3], n)
71
+ case operator
72
+ when "==" then left == right
73
+ when "!=" then left != right
74
+ when "<" then left < right
75
+ when "<=" then left <= right
76
+ when ">" then left > right
77
+ when ">=" then left >= right
78
+ else left.send(operator, right)
79
+ end
80
+ end
81
+ end
82
+
83
+ class Parser
84
+ def initialize(tokens)
85
+ @tokens = tokens
86
+ @position = 0
87
+ end
88
+
89
+ def parse
90
+ result = parse_expression
91
+ unless @position == @tokens.size
92
+ raise InvalidExpression, "unexpected #{peek.inspect} in plural expression"
93
+ end
94
+
95
+ result
96
+ end
97
+
98
+ def parse_expression
99
+ condition = binary(1)
100
+ return condition unless take("?")
101
+
102
+ positive = parse_expression
103
+ need(":")
104
+ [:conditional, condition, positive, parse_expression]
105
+ end
106
+
107
+ def binary(level)
108
+ return unary if level > 6
109
+
110
+ left = binary(level + 1)
111
+ while PRECEDENCE[peek] == level
112
+ operator = peek
113
+ @position += 1
114
+ left = [:binary, operator, left, binary(level + 1)]
115
+ end
116
+ left
117
+ end
118
+
119
+ def unary
120
+ return [:not, unary] if take("!")
121
+ return [:negate, unary] if take("-")
122
+ return [:positive, unary] if take("+")
123
+
124
+ atom
125
+ end
126
+
127
+ def atom
128
+ token = peek
129
+ @position += 1
130
+ case token
131
+ when /\A\d+\z/ then [:number, token.to_i]
132
+ when "n" then [:variable]
133
+ when "(" then parse_expression.tap { need(")") }
134
+ else raise InvalidExpression, "unexpected #{token.inspect} in plural expression"
135
+ end
136
+ end
137
+
138
+ def peek
139
+ @tokens[@position]
140
+ end
141
+
142
+ def take(token)
143
+ return false unless peek == token
144
+
145
+ @position += 1
146
+ true
147
+ end
148
+
149
+ def need(token)
150
+ return if take(token)
151
+
152
+ raise InvalidExpression, "expected #{token.inspect} in plural expression"
153
+ end
154
+ end
155
+ end
156
+ end
@@ -63,7 +63,9 @@ module FastGettext
63
63
  # if overwritten by user( FastGettext.pluralisation_rule = xxx) use it,
64
64
  # otherwise fall back to repo or to default lambda
65
65
  def pluralisation_rule
66
- Thread.current[:fast_gettext_pluralisation_rule] || current_repository.pluralisation_rule || DEFAULT_PLURALIZATION_RULE
66
+ Thread.current[:fast_gettext_pluralisation_rule] ||
67
+ current_repository.pluralisation_rule ||
68
+ DEFAULT_PLURALIZATION_RULE
67
69
  end
68
70
 
69
71
  def cache
@@ -72,7 +74,7 @@ module FastGettext
72
74
 
73
75
  def reload!
74
76
  cache.reload!
75
- translation_repositories.values.each(&:reload)
77
+ translation_repositories.each_value(&:reload)
76
78
  end
77
79
 
78
80
  # global, since re-parsing whole folders takes too much time...
@@ -94,7 +96,7 @@ module FastGettext
94
96
  end
95
97
 
96
98
  def cached_plural_find(*keys)
97
- key = '||||' + keys * '||||'
99
+ key = "||||#{keys * '||||'}"
98
100
  cache.fetch(key) { current_repository.plural(*keys) }
99
101
  end
100
102
 
@@ -134,7 +136,8 @@ module FastGettext
134
136
  # IE6/7 de
135
137
  # nil if nothing matches
136
138
  def best_locale_in(locales)
137
- formatted_sorted_locales(locales).each do |candidate|
139
+ candidates = plain_locale(locales) || formatted_sorted_locales(locales)
140
+ candidates.each do |candidate|
138
141
  return candidate unless available_locales
139
142
  return candidate if available_locales.include?(candidate)
140
143
  return candidate[0..1] if available_locales.include?(candidate[0..1]) # available locales include a langauge
@@ -160,9 +163,21 @@ module FastGettext
160
163
 
161
164
  private
162
165
 
166
+ # A single locale already in the de / de_DE form, as set_locale gets it on
167
+ # every I18n.locale= or with_locale (gettext_i18n_rails): parsing it as
168
+ # an Accept-Language header would give the same one candidate.
169
+ PLAIN_LOCALE = /\A[a-z]{2,3}(?:_[A-Z]{2,3})?\z/
170
+ private_constant :PLAIN_LOCALE
171
+
172
+ def plain_locale(locale)
173
+ locale = locale.name if locale.is_a?(Symbol)
174
+ [locale.dup] if locale.is_a?(String) && PLAIN_LOCALE.match?(locale)
175
+ end
176
+
163
177
  # de-de,DE-CH;q=0.9 -> ['de_DE','de_CH']
164
178
  def formatted_sorted_locales(locales)
165
- found = weighted_locales(locales).reject(&:empty?).sort_by(&:last).reverse # sort them by weight which is the last entry
179
+ # sort them by weight which is the last entry
180
+ found = weighted_locales(locales).reject(&:empty?).sort_by(&:last).reverse
166
181
  found.flatten.map { |l| format_locale(l) }
167
182
  end
168
183
 
@@ -173,7 +188,7 @@ module FastGettext
173
188
  found = [[]]
174
189
  locales.split(',').each do |part|
175
190
  if part.include? ';q=' # contains language and weight ?
176
- found.last << part.split(/;q=/)
191
+ found.last << part.split(';q=')
177
192
  found.last.flatten!
178
193
  found << []
179
194
  else
@@ -185,7 +200,7 @@ module FastGettext
185
200
 
186
201
  # de-de -> de_DE
187
202
  def format_locale(locale)
188
- locale.sub(/^([a-zA-Z]{2,3})[-_]([a-zA-Z]{2,3})$/) { $1.downcase + '_' + $2.upcase }
203
+ locale.sub(/^([a-zA-Z]{2,3})[-_]([a-zA-Z]{2,3})$/) { "#{$1.downcase}_#{$2.upcase}" }
189
204
  end
190
205
 
191
206
  def switch_cache
@@ -2,7 +2,7 @@
2
2
 
3
3
  module FastGettext
4
4
  TRANSLATION_METHODS = [:_, :n_, :s_, :p_, :ns_, :np_].freeze
5
- NIL_BLOCK = -> { nil }
5
+ NIL_BLOCK = -> {}
6
6
 
7
7
  # this module should be included
8
8
  # Responsibility:
@@ -90,6 +90,7 @@ module FastGettext
90
90
 
91
91
  module TranslationAliased
92
92
  include Translation
93
+
93
94
  TRANSLATION_METHODS.each { |m| alias_method "#{m.to_s.delete('_')}gettext", m }
94
95
  end
95
96
 
@@ -8,7 +8,9 @@ class TranslationKey < ActiveRecord::Base
8
8
  validates_uniqueness_of :key
9
9
  validates_presence_of :key
10
10
 
11
- attr_accessible :key, :translations, :translations_attributes if ActiveRecord::VERSION::MAJOR == 3 || defined?(ProtectedAttributes)
11
+ if ActiveRecord::VERSION::MAJOR == 3 || defined?(ProtectedAttributes)
12
+ attr_accessible :key, :translations, :translations_attributes
13
+ end
12
14
 
13
15
  before_save :normalize_newlines
14
16
 
@@ -20,13 +22,11 @@ class TranslationKey < ActiveRecord::Base
20
22
  end
21
23
 
22
24
  def self.available_locales
23
- @available_locales ||= begin
24
- if ActiveRecord::VERSION::MAJOR >= 3
25
- TranslationText.group(:locale).count
26
- else
27
- TranslationText.count(group: :locale)
28
- end.keys.sort
29
- end
25
+ @available_locales ||= if ActiveRecord::VERSION::MAJOR >= 3
26
+ TranslationText.group(:locale).count
27
+ else
28
+ TranslationText.count(group: :locale)
29
+ end.keys.sort
30
30
  end
31
31
 
32
32
  def self.newline_normalize(string)
@@ -4,7 +4,9 @@ class TranslationText < ActiveRecord::Base
4
4
  belongs_to :translation_key, class_name: 'TranslationKey'
5
5
  validates_presence_of :locale
6
6
  validates_uniqueness_of :locale, scope: :translation_key_id
7
- attr_accessible :text, :locale, :translation_key, :translation_key_id if ActiveRecord::VERSION::MAJOR == 3 || defined?(ProtectedAttributes)
7
+ if ActiveRecord::VERSION::MAJOR == 3 || defined?(ProtectedAttributes)
8
+ attr_accessible :text, :locale, :translation_key, :translation_key_id
9
+ end
8
10
  after_update :expire_cache
9
11
 
10
12
  protected
@@ -11,7 +11,7 @@ module FastGettext
11
11
  class Merge < Base
12
12
  def initialize(name, options = {})
13
13
  clear
14
- super(name, options)
14
+ super
15
15
  options.fetch(:chain, []).each do |repo|
16
16
  add_repo(repo)
17
17
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'fast_gettext/translation_repository/base'
4
+ require 'fast_gettext/plural_expression'
4
5
  require 'yaml'
5
6
 
6
7
  module FastGettext
@@ -24,12 +25,14 @@ module FastGettext
24
25
  end
25
26
  end
26
27
 
28
+ # n_() asks for this on every call: each rule is compiled once, keyed by
29
+ # its text, so locales with different rules get their own lambda and
30
+ # locales with the same rule share one.
27
31
  def pluralisation_rule
28
32
  return unless rule = self['pluralisation_rule']
29
33
 
30
- ->(n) do # rubocop:disable Lint/UnusedBlockArgument n can be used from pluralisation_rule code
31
- eval(rule) # rubocop:disable Security/Eval TODO remove eval
32
- end
34
+ (@pluralisation_rules ||= {})[rule] ||=
35
+ PluralExpression.compile(rule)
33
36
  end
34
37
 
35
38
  def reload
@@ -79,7 +82,7 @@ module FastGettext
79
82
  result
80
83
  end
81
84
 
82
- def yaml_dot_notation(a, b) # rubocop:disable Naming/UncommunicativeMethodParamName
85
+ def yaml_dot_notation(a, b)
83
86
  a ? "#{a}.#{b}" : b
84
87
  end
85
88
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module FastGettext
4
- VERSION = Version = '4.1.1' # rubocop:disable Naming/ConstantName
4
+ VERSION = Version = '4.3.0' # rubocop:disable Naming/ConstantName
5
5
  end
data/lib/fast_gettext.rb CHANGED
@@ -11,7 +11,7 @@ module FastGettext
11
11
  extend FastGettext::Storage
12
12
  extend FastGettext::Translation
13
13
 
14
- LOCALE_REX = /^[a-z]{2,3}$|^[a-z]{2,3}_[A-Z]{2,3}$/.freeze
14
+ LOCALE_REX = /^[a-z]{2,3}$|^[a-z]{2,3}_[A-Z]{2,3}$/
15
15
  NAMESPACE_SEPARATOR = '|'
16
16
  CONTEXT_SEPARATOR = "\004"
17
17
 
@@ -30,7 +30,7 @@ module FastGettext
30
30
 
31
31
  # deprecated, just a crutch to migrate to new api
32
32
  def self.allow_invalid_keys!
33
- eval(<<~CODE)
33
+ eval(<<~CODE, binding, __FILE__, __LINE__ + 1)
34
34
  class ::String
35
35
  alias :_fast_gettext_old_format_m :%
36
36
  def %(*args)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: fast_gettext
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.1.1
4
+ version: 4.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Michael Grosser
@@ -188,6 +188,7 @@ files:
188
188
  - lib/fast_gettext.rb
189
189
  - lib/fast_gettext/cache.rb
190
190
  - lib/fast_gettext/mo_file.rb
191
+ - lib/fast_gettext/plural_expression.rb
191
192
  - lib/fast_gettext/po_file.rb
192
193
  - lib/fast_gettext/storage.rb
193
194
  - lib/fast_gettext/translation.rb
@@ -221,7 +222,7 @@ required_ruby_version: !ruby/object:Gem::Requirement
221
222
  requirements:
222
223
  - - ">="
223
224
  - !ruby/object:Gem::Version
224
- version: 3.2.0
225
+ version: 3.3.0
225
226
  required_rubygems_version: !ruby/object:Gem::Requirement
226
227
  requirements:
227
228
  - - ">="