Skip to content

Commit c16460e

Browse files
authored
Merge pull request #395 from stereobooster/interpolate-for-arrays
Interpolate for arrays
2 parents 6636178 + 7ffc496 commit c16460e

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

lib/i18n/backend/base.rb

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -151,15 +151,26 @@ def pluralize(locale, entry, count)
151151
entry[key]
152152
end
153153

154-
# Interpolates values into a given string.
154+
# Interpolates values into a given subject.
155155
#
156-
# interpolate "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X'
156+
# if the given subject is a string then:
157+
# method interpolates "file %{file} opened by %%{user}", :file => 'test.txt', :user => 'Mr. X'
157158
# # => "file test.txt opened by %{user}"
158-
def interpolate(locale, string, values = {})
159-
if string.is_a?(::String) && !values.empty?
160-
I18n.interpolate(string, values)
159+
#
160+
# if the given subject is an array then:
161+
# each element of the array is recursively interpolated (until it finds a string)
162+
# method interpolates ["yes, %{user}", ["maybe no, %{user}, "no, %{user}"]], :user => "bartuz"
163+
# # => "["yes, bartuz",["maybe no, bartuz", "no, bartuz"]]"
164+
165+
166+
def interpolate(locale, subject, values = {})
167+
return subject if values.empty?
168+
169+
case subject
170+
when ::String then I18n.interpolate(subject, values)
171+
when ::Array then subject.map { |element| interpolate(locale, element, values) }
161172
else
162-
string
173+
subject
163174
end
164175
end
165176

lib/i18n/tests/interpolation.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,11 @@ module Interpolation
5454
assert_equal 'Hi Yehuda!', interpolate(:interpolate, :name => 'Yehuda')
5555
end
5656

57+
test "interpolation: given an array interpolates each element" do
58+
I18n.backend.store_translations(:en, :array_interpolate => ['Hi', 'Mr. %{name}', 'or sir %{name}'])
59+
assert_equal ['Hi', 'Mr. Bartuz', 'or sir Bartuz'], interpolate(:array_interpolate, :name => 'Bartuz')
60+
end
61+
5762
test "interpolation: given the translation is in utf-8 it still works" do
5863
assert_equal 'Häi David!', interpolate(:default => 'Häi %{name}!', :name => 'David')
5964
end

0 commit comments

Comments
 (0)