Skip to content
This repository
Browse code

I18n: applied Luca Guidi's patch for better #interpolate performance

[#943 state:resolved]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information...
commit be4ae1f5264d6593e9dec479af4503c4bde2877e 1 parent efa6620
Sven Fuchs svenfuchs authored jeremy committed
37 activesupport/lib/active_support/vendor/i18n-0.0.1/i18n/backend/simple.rb
@@ -3,6 +3,9 @@
3 3 module I18n
4 4 module Backend
5 5 class Simple
  6 + INTERPOLATION_RESERVED_KEYS = %w(scope default)
  7 + MATCH = /(\\\\)?\{\{([^\}]+)\}\}/
  8 +
6 9 # Accepts a list of paths to translation files. Loads translations from
7 10 # plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml
8 11 # for details.
@@ -114,29 +117,29 @@ def pluralize(locale, entry, count)
114 117 # the <tt>{{...}}</tt> key in a string (once for the string and once for the
115 118 # interpolation).
116 119 def interpolate(locale, string, values = {})
117   - return string if !string.is_a?(String)
  120 + return string unless string.is_a?(String)
118 121
119 122 string = string.gsub(/%d/, '{{count}}').gsub(/%s/, '{{value}}')
  123 +
120 124 if string.respond_to?(:force_encoding)
121   - original_encoding = string.encoding
122   - string.force_encoding(Encoding::BINARY)
123   - end
124   - s = StringScanner.new(string)
125   -
126   - while s.skip_until(/\{\{/)
127   - s.string[s.pos - 3, 1] = '' and next if s.pre_match[-1, 1] == '\\'
128   - start_pos = s.pos - 2
129   - key = s.scan_until(/\}\}/)[0..-3]
130   - end_pos = s.pos - 1
  125 + original_encoding = string.encoding
  126 + string.force_encoding(Encoding::BINARY)
  127 + end
131 128
132   - raise ReservedInterpolationKey.new(key, string) if %w(scope default).include?(key)
133   - raise MissingInterpolationArgument.new(key, string) unless values.has_key? key.to_sym
  129 + result = string.gsub(MATCH) do
  130 + escaped, pattern, key = $1, $2, $2.to_sym
134 131
135   - s.string[start_pos..end_pos] = values[key.to_sym].to_s
136   - s.unscan
  132 + if escaped
  133 + pattern
  134 + elsif INTERPOLATION_RESERVED_KEYS.include?(pattern)
  135 + raise ReservedInterpolationKey.new(pattern, string)
  136 + elsif !values.include?(key)
  137 + raise MissingInterpolationArgument.new(pattern, string)
  138 + else
  139 + values[key].to_s
  140 + end
137 141 end
138   -
139   - result = s.string
  142 +
140 143 result.force_encoding(original_encoding) if original_encoding
141 144 result
142 145 end

0 comments on commit be4ae1f

Please sign in to comment.
Something went wrong with that request. Please try again.