Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interpolate for arrays #395

Merged
merged 6 commits into from Jan 19, 2018
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 17 additions & 6 deletions lib/i18n/backend/base.rb
Expand Up @@ -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

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