diff --git a/lib/i18n/backend/base.rb b/lib/i18n/backend/base.rb index 668a4221..fe30e151 100644 --- a/lib/i18n/backend/base.rb +++ b/lib/i18n/backend/base.rb @@ -147,15 +147,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 diff --git a/lib/i18n/tests/interpolation.rb b/lib/i18n/tests/interpolation.rb index c457b3d7..27c99c3b 100644 --- a/lib/i18n/tests/interpolation.rb +++ b/lib/i18n/tests/interpolation.rb @@ -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