Skip to content
Browse files

Implemented lambda support for #translate.

  • Loading branch information...
1 parent bde2b62 commit 1113c6068a44e3aa70b3733d52ce3212d573503e @clemens clemens committed with Apr 17, 2009
Showing with 42 additions and 0 deletions.
  1. +1 −0 lib/i18n/backend/simple.rb
  2. +41 −0 test/simple_backend_test.rb
View
1 lib/i18n/backend/simple.rb
@@ -31,6 +31,7 @@ def translate(locale, key, options = {})
values = options.reject { |name, value| reserved.include?(name) }
entry = lookup(locale, key, scope) || resolve(locale, key, default, options) || raise(I18n::MissingTranslationData.new(locale, key, options))
+ entry = entry.call(values) if entry.is_a? Proc
entry = pluralize(locale, entry, count)
entry = interpolate(locale, entry, values)
entry
View
41 test/simple_backend_test.rb
@@ -196,6 +196,47 @@ def test_translate_with_a_bogus_key_and_no_default_raises_missing_translation_da
end
end
+class I18nSimpleBackendTranslateLambdaTest < Test::Unit::TestCase
+ include I18nSimpleBackendTestSetup
+
+ def test_translate_simple_proc
+ setup_proc_translation
+ assert_equal 'bar=bar, baz=baz, foo=foo', @backend.translate('en', :a_lambda, :foo => 'foo', :bar => 'bar', :baz => 'baz')
+ end
+
+ def test_translate_proc_in_defaults
+ setup_proc_translation
+ assert_equal 'bar=bar, baz=baz, foo=foo', @backend.translate('en', :does_not_exist, :default => :a_lambda, :foo => 'foo', :bar => 'bar', :baz => 'baz')
+ assert_equal 'bar=bar, baz=baz, foo=foo', @backend.translate('en', :does_not_exist, :default => [:does_not_exist_2, :does_not_exist_3, :a_lambda], :foo => 'foo', :bar => 'bar', :baz => 'baz')
+ end
+
+ def test_translate_proc_with_pluralize
+ setup_proc_translation
+ params = { :zero => 'zero', :one => 'one', :other => 'other' }
+ assert_equal 'zero', @backend.translate('en', :lambda_for_pluralize, params.merge(:count => 0))
+ assert_equal 'one', @backend.translate('en', :lambda_for_pluralize, params.merge(:count => 1))
+ assert_equal 'other', @backend.translate('en', :lambda_for_pluralize, params.merge(:count => 2))
+ end
+
+ def test_translate_proc_with_interpolate
+ setup_proc_translation
+ assert_equal 'bar baz foo', @backend.translate('en', :lambda_for_interpolate, :foo => 'foo', :bar => 'bar', :baz => 'baz')
+ end
+
+ private
+ def setup_proc_translation
+ @backend.store_translations 'en', {
+ :a_lambda => lambda { |attributes|
+ attributes.keys.sort_by(&:to_s).collect { |key| "#{key}=#{attributes[key]}"}.join(', ')
+ },
+ :lambda_for_pluralize => lambda { |attributes| attributes },
+ :lambda_for_interpolate => lambda { |attributes|
+ "{{#{attributes.keys.sort_by(&:to_s).join('}} {{')}}}"
+ }
+ }
+ end
+end
+
class I18nSimpleBackendLookupTest < Test::Unit::TestCase
include I18nSimpleBackendTestSetup

0 comments on commit 1113c60

Please sign in to comment.
Something went wrong with that request. Please try again.