Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/i18n/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 5 additions & 3 deletions lib/i18n/interpolate/ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
# https://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 "%<foo>.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.
Expand All @@ -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
Expand Down
17 changes: 17 additions & 0 deletions test/i18n/interpolate_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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