diff --git a/lib/i18n/config.rb b/lib/i18n/config.rb index 9c4221c7..10645017 100644 --- a/lib/i18n/config.rb +++ b/lib/i18n/config.rb @@ -145,5 +145,21 @@ def enforce_available_locales def enforce_available_locales=(enforce_available_locales) @@enforce_available_locales = enforce_available_locales end + + # Returns the current interpolation patterns. Defaults to + # I18n::DEFAULT_INTERPOLATION_PATTERNS. + def interpolation_patterns + @@interpolation_patterns ||= I18n::DEFAULT_INTERPOLATION_PATTERNS.dup + end + + # Sets the current interpolation patterns. Used to set a interpolation + # patterns. + # + # E.g. using {{}} as a placeholder like "{{hello}}, world!": + # + # I18n.config.interpolation_patterns << /\{\{(\w+)\}\}/ + def interpolation_patterns=(interpolation_patterns) + @@interpolation_patterns = interpolation_patterns + end end end diff --git a/lib/i18n/interpolate/ruby.rb b/lib/i18n/interpolate/ruby.rb index d2fdda75..b5586b2a 100644 --- a/lib/i18n/interpolate/ruby.rb +++ b/lib/i18n/interpolate/ruby.rb @@ -2,11 +2,13 @@ # http://github.com/mutoh/gettext/blob/f6566738b981fe0952548c421042ad1e0cdfb31e/lib/gettext/core_ext/string.rb module I18n - INTERPOLATION_PATTERN = Regexp.union( + DEFAULT_INTERPOLATION_PATTERNS = [ /%%/, /%\{(\w+)\}/, # matches placeholders like "%{foo}" /%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/ # matches placeholders like "%.d" - ) + ].freeze + INTERPOLATION_PATTERN = Regexp.union(DEFAULT_INTERPOLATION_PATTERNS) + deprecate_constant :INTERPOLATION_PATTERN if method_defined? :INTERPOLATION_PATTERN class << self # Return String or raises MissingInterpolationArgument exception. @@ -18,7 +20,7 @@ def interpolate(string, values) end def interpolate_hash(string, values) - string.gsub(INTERPOLATION_PATTERN) do |match| + string.gsub(Regexp.union(config.interpolation_patterns)) do |match| if match == '%%' '%' else diff --git a/test/i18n/interpolate_test.rb b/test/i18n/interpolate_test.rb index 78e54d3b..1180181f 100644 --- a/test/i18n/interpolate_test.rb +++ b/test/i18n/interpolate_test.rb @@ -89,3 +89,20 @@ def teardown I18n.interpolate("%{first} %{last}", :first => 'Masao') end end + +class I18nCustomInterpolationPatternTest < I18n::TestCase + def setup + super + @old_interpolation_patterns = I18n.config.interpolation_patterns + I18n.config.interpolation_patterns << /\{\{(\w+)\}\}/ + end + + def teardown + I18n.config.interpolation_patterns = @old_interpolation_patterns + super + end + + test "String interpolation can use custom interpolation pattern" do + assert_equal "Masao Mutoh", I18n.interpolate("{{first}} {{last}}", :first => "Masao", :last => "Mutoh") + end +end