the translate liquid filter handles interpolation

did committed Dec 28, 2015
commit e9e8d883f24b5a9b3e56bf1805138aede5f4c9d5
Showing 2 changed files with 25 additions and 9 deletions
locomotive/steam/services/translator_service.rb b/lib/locomotive/steam/services/translator_service.rb +8 -2
@@ @@ -14,7 +14,7 @@ module Locomotive
#
def translate(input, options = {})
locale = options['locale'] || self.current_locale
- scope = options['scope']
+ scope = options.delete('scope')
if scope.blank?
values = repository.by_key(input).try(:values) || {}
@@ @@ -22,7 +22,7 @@ module Locomotive
# FIXME: important to check if the returned value is nil (instead of nil + false)
# false being reserved for an existing key but without provided translation)
if (translation = values[locale.to_s]).present?
- translation
+ _translate(translation, options)
else
Locomotive::Common::Logger.warn "Missing translation '#{input}' for the '#{locale}' locale".yellow
ActiveSupport::Notifications.instrument('steam.missing_translation', input: input, locale: locale)
@@ @@ -33,6 +33,12 @@ module Locomotive
end
end
+ private
+
+ def _translate(string, options)
+ ::Liquid::Template.parse(string).render(options)
+ end
+
end
end
spec/unit/services/translator_service_spec.rb +17 -7
@@ @@ -8,15 +8,16 @@ describe Locomotive::Steam::TranslatorService do
describe '#translate' do
- let(:input) { 'example_test' }
- let(:locale) { nil }
- let(:scope) { nil }
+ let(:input) { 'example_test' }
+ let(:locale) { nil }
+ let(:scope) { nil }
+ let(:interpolation) { {} }
before do
allow(repository).to receive(:by_key).with('example_test').and_return(translation)
end
- subject { service.translate(input, 'locale' => locale, 'scope' => scope) }
+ subject { service.translate(input, interpolation.merge('locale' => locale, 'scope' => scope)) }
describe 'existing translation' do
@@ @@ -24,14 +25,14 @@ describe Locomotive::Steam::TranslatorService do
it { is_expected.to eq 'Example text' }
- context 'specifying a locale' do
+ describe 'specifying a locale' do
let(:locale) { 'es' }
it { is_expected.to eq 'Texto de ejemplo' }
end
- context "specifying a locale that doesn't exist" do
+ describe "specifying a locale that doesn't exist" do
let(:locale) { 'nl' }
@@ @@ -41,7 +42,7 @@ describe Locomotive::Steam::TranslatorService do
end
- context 'specifying a scope' do
+ context 'with a scope' do
let(:input) { 'fr' }
let(:locale) { 'en' }
@@ @@ -51,6 +52,15 @@ describe Locomotive::Steam::TranslatorService do
end
+ describe 'interpolation' do
+
+ let(:interpolation) { { 'name' => 'John' } }
+ let(:translation) { instance_double('Translation', values: { 'en' => 'Hello {{ name }}', 'es' => 'Texto de ejemplo' }) }
+
+ it { is_expected.to eq 'Hello John' }
+
+ end
+
end
describe 'missing translation' do