Skip to content

Commit

Permalink
Merge pull request #395 from stereobooster/interpolate-for-arrays
Browse files Browse the repository at this point in the history
Interpolate for arrays
  • Loading branch information
radar committed Jan 19, 2018
2 parents 6636178 + 7ffc496 commit c16460e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
23 changes: 17 additions & 6 deletions lib/i18n/backend/base.rb
Expand Up @@ -151,15 +151,26 @@ def pluralize(locale, entry, count)
entry[key]
end

# Interpolates values into a given string.
# Interpolates values into a given subject.
#
# interpolate "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X'
# if the given subject is a string then:
# method interpolates "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X'
# # => "file test.txt opened by %{user}"
def interpolate(locale, string, values = {})
if string.is_a?(::String) && !values.empty?
I18n.interpolate(string, values)
#
# if the given subject is an array then:
# each element of the array is recursively interpolated (until it finds a string)
# method interpolates ["yes, %{user}", ["maybe no, %{user}, "no, %{user}"]], :user => "bartuz"
# # => "["yes, bartuz",["maybe no, bartuz", "no, bartuz"]]"


def interpolate(locale, subject, values = {})
return subject if values.empty?

case subject
when ::String then I18n.interpolate(subject, values)
when ::Array then subject.map { |element| interpolate(locale, element, values) }
else
string
subject
end
end

Expand Down
5 changes: 5 additions & 0 deletions lib/i18n/tests/interpolation.rb
Expand Up @@ -54,6 +54,11 @@ module Interpolation
assert_equal 'Hi Yehuda!', interpolate(:interpolate, :name => 'Yehuda')
end

test "interpolation: given an array interpolates each element" do
I18n.backend.store_translations(:en, :array_interpolate => ['Hi', 'Mr. %{name}', 'or sir %{name}'])
assert_equal ['Hi', 'Mr. Bartuz', 'or sir Bartuz'], interpolate(:array_interpolate, :name => 'Bartuz')
end

test "interpolation: given the translation is in utf-8 it still works" do
assert_equal 'Häi David!', interpolate(:default => 'Häi %{name}!', :name => 'David')
end
Expand Down

0 comments on commit c16460e

Please sign in to comment.