Skip to content
Browse files

remove whitespace and backport Tarmo's fix for making simple backend …

…able to store false values (and not confuse them with nil) http://github.com/rails/rails/commit/d69b4b7bea28fcab04f61afe381e06fa8e37b429
  • Loading branch information...
1 parent 250c045 commit 39d9a47da14b5f3ba126af48923af8c30e135166 @svenfuchs committed Oct 25, 2008
Showing with 226 additions and 210 deletions.
  1. +41 −39 lib/i18n.rb
  2. +52 −38 lib/i18n/backend/simple.rb
  3. +3 −3 lib/i18n/exceptions.rb
  4. +1 −1 test/all.rb
  5. +14 −14 test/i18n_exceptions_test.rb
  6. +23 −23 test/i18n_test.rb
  7. +92 −92 test/simple_backend_test.rb
View
80 lib/i18n.rb
@@ -2,39 +2,39 @@
# Sven Fuchs (http://www.artweb-design.de),
# Joshua Harvey (http://www.workingwithrails.com/person/759-joshua-harvey),
# Saimon Moore (http://saimonmoore.net),
-# Stephan Soller (http://www.arkanis-development.de/)
+# Stephan Soller (http://www.arkanis-development.de/)
# Copyright:: Copyright (c) 2008 The Ruby i18n Team
# License:: MIT
require 'i18n/backend/simple'
require 'i18n/exceptions'
-module I18n
+module I18n
@@backend = nil
- @@load_path = []
+ @@load_path = nil
@@default_locale = :'en-US'
@@exception_handler = :default_exception_handler
-
+
class << self
# Returns the current backend. Defaults to +Backend::Simple+.
def backend
@@backend ||= Backend::Simple.new
end
-
+
# Sets the current backend. Used to set a custom backend.
- def backend=(backend)
+ def backend=(backend)
@@backend = backend
end
-
+
# Returns the current default locale. Defaults to 'en-US'
def default_locale
- @@default_locale
+ @@default_locale
end
-
+
# Sets the current default locale. Used to set a custom default locale.
- def default_locale=(locale)
- @@default_locale = locale
+ def default_locale=(locale)
+ @@default_locale = locale
end
-
+
# Returns the current locale. Defaults to I18n.default_locale.
def locale
Thread.current[:locale] ||= default_locale
@@ -44,46 +44,48 @@ def locale
def locale=(locale)
Thread.current[:locale] = locale
end
-
+
# Sets the exception handler.
def exception_handler=(exception_handler)
@@exception_handler = exception_handler
end
-
- # Allow clients to register paths providing translation data sources. The
+
+ # Allow clients to register paths providing translation data sources. The
# backend defines acceptable sources.
#
# E.g. the provided SimpleBackend accepts a list of paths to translation
# files which are either named *.rb and contain plain Ruby Hashes or are
- # named *.yml and contain YAML data. So for the SimpleBackend clients may
+ # named *.yml and contain YAML data. So for the SimpleBackend clients may
# register translation files like this:
# I18n.load_path << 'path/to/locale/en-US.yml'
def load_path
- @@load_path
+ @@load_path ||= []
end
+ # Sets the load path instance. Custom implementations are expected to
+ # behave like a Ruby Array.
def load_path=(load_path)
@@load_path = load_path
end
-
- # Translates, pluralizes and interpolates a given key using a given locale,
+
+ # Translates, pluralizes and interpolates a given key using a given locale,
# scope, and default, as well as interpolation values.
#
# *LOOKUP*
#
- # Translation data is organized as a nested hash using the upper-level keys
- # as namespaces. <em>E.g.</em>, ActionView ships with the translation:
+ # Translation data is organized as a nested hash using the upper-level keys
+ # as namespaces. <em>E.g.</em>, ActionView ships with the translation:
# <tt>:date => {:formats => {:short => "%b %d"}}</tt>.
- #
- # Translations can be looked up at any level of this hash using the key argument
- # and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
+ #
+ # Translations can be looked up at any level of this hash using the key argument
+ # and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
# returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>.
- #
- # Key can be either a single key or a dot-separated key (both Strings and Symbols
+ #
+ # Key can be either a single key or a dot-separated key (both Strings and Symbols
# work). <em>E.g.</em>, the short format can be looked up using both:
# I18n.t 'date.formats.short'
# I18n.t :'date.formats.short'
- #
+ #
# Scope can be either a single key, a dot-separated key or an array of keys
# or dot-separated keys. Keys and scopes can be combined freely. So these
# examples will all look up the same short date format:
@@ -96,9 +98,9 @@ def load_path=(load_path)
#
# Translations can contain interpolation variables which will be replaced by
# values passed to #translate as part of the options hash, with the keys matching
- # the interpolation variable names.
+ # the interpolation variable names.
#
- # <em>E.g.</em>, with a translation <tt>:foo => "foo {{bar}}"</tt> the option
+ # <em>E.g.</em>, with a translation <tt>:foo => "foo {{bar}}"</tt> the option
# value for the key +bar+ will be interpolated into the translation:
# I18n.t :foo, :bar => 'baz' # => 'foo baz'
#
@@ -107,7 +109,7 @@ def load_path=(load_path)
# Translation data can contain pluralized translations. Pluralized translations
# are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>.
#
- # Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
+ # Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
# pluralization rules. Other algorithms can be supported by custom backends.
#
# This returns the singular version of a pluralized translation:
@@ -116,9 +118,9 @@ def load_path=(load_path)
# These both return the plural version of a pluralized translation:
# I18n.t :foo, :count => 0 # => 'Foos'
# I18n.t :foo, :count => 2 # => 'Foos'
- #
- # The <tt>:count</tt> option can be used both for pluralization and interpolation.
- # <em>E.g.</em>, with the translation
+ #
+ # The <tt>:count</tt> option can be used both for pluralization and interpolation.
+ # <em>E.g.</em>, with the translation
# <tt>:foo => ['{{count}} foo', '{{count}} foos']</tt>, count will
# be interpolated to the pluralized translation:
# I18n.t :foo, :count => 1 # => '1 foo'
@@ -128,11 +130,11 @@ def load_path=(load_path)
# This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found:
# I18n.t :foo, :default => 'default'
#
- # This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
+ # This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
# translation for <tt>:foo</tt> was found:
# I18n.t :foo, :default => :bar
#
- # Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
+ # Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
# or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found.
# I18n.t :foo, :default => [:bar, 'default']
#
@@ -152,17 +154,17 @@ def translate(key, options = {})
rescue I18n::ArgumentError => e
raise e if options[:raise]
send @@exception_handler, e, locale, key, options
- end
+ end
alias :t :translate
-
+
# Localizes certain objects, such as dates and numbers to local formatting.
def localize(object, options = {})
locale = options[:locale] || I18n.locale
format = options[:format] || :default
backend.localize(locale, object, format)
end
alias :l :localize
-
+
protected
# Handles exceptions raised in the backend. All exceptions except for
# MissingTranslationData exceptions are re-raised. When a MissingTranslationData
@@ -172,7 +174,7 @@ def default_exception_handler(exception, locale, key, options)
return exception.message if MissingTranslationData === exception
raise exception
end
-
+
# Merges the given locale, key and scope into a single array of keys.
# Splits keys that contain dots into multiple keys. Makes sure all
# keys are Symbols.
View
90 lib/i18n/backend/simple.rb
@@ -1,26 +1,26 @@
-require 'strscan'
+require 'yaml'
module I18n
module Backend
class Simple
INTERPOLATION_RESERVED_KEYS = %w(scope default)
MATCH = /(\\\\)?\{\{([^\}]+)\}\}/
- # Accepts a list of paths to translation files. Loads translations from
+ # Accepts a list of paths to translation files. Loads translations from
# plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml
# for details.
def load_translations(*filenames)
filenames.each {|filename| load_file filename }
end
-
- # Stores translations for the given locale in memory.
+
+ # Stores translations for the given locale in memory.
# This uses a deep merge for the translations hash, so existing
# translations will be overwritten by new ones only at the deepest
# level of the hash.
def store_translations(locale, data)
merge_translations(locale, data)
end
-
+
def translate(locale, key, options = {})
raise InvalidLocale.new(locale) if locale.nil?
return key.map{|k| translate locale, k, options } if key.is_a? Array
@@ -30,18 +30,24 @@ def translate(locale, key, options = {})
options.delete(:default)
values = options.reject{|name, value| reserved.include? name }
- entry = lookup(locale, key, scope) || default(locale, default, options) || raise(I18n::MissingTranslationData.new(locale, key, options))
+ entry = lookup(locale, key, scope)
+ if entry.nil?
+ entry = default(locale, default, options)
+ if entry.nil?
+ raise(I18n::MissingTranslationData.new(locale, key, options))
+ end
+ end
entry = pluralize locale, entry, count
entry = interpolate locale, entry, values
entry
end
-
- # Acts the same as +strftime+, but returns a localized version of the
- # formatted date string. Takes a key from the date/time formats
- # translations as a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
+
+ # Acts the same as +strftime+, but returns a localized version of the
+ # formatted date string. Takes a key from the date/time formats
+ # translations as a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>).
def localize(locale, object, format = :default)
raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)
-
+
type = object.respond_to?(:sec) ? 'time' : 'date'
# TODO only translate these if format is a String?
formats = translate(locale, :"#{type}.formats")
@@ -51,56 +57,66 @@ def localize(locale, object, format = :default)
# TODO only translate these if the format string is actually present
# TODO check which format strings are present, then bulk translate then, then replace them
- format.gsub!(/%a/, translate(locale, :"date.abbr_day_names")[object.wday])
+ format.gsub!(/%a/, translate(locale, :"date.abbr_day_names")[object.wday])
format.gsub!(/%A/, translate(locale, :"date.day_names")[object.wday])
format.gsub!(/%b/, translate(locale, :"date.abbr_month_names")[object.mon])
format.gsub!(/%B/, translate(locale, :"date.month_names")[object.mon])
format.gsub!(/%p/, translate(locale, :"time.#{object.hour < 12 ? :am : :pm}")) if object.respond_to? :hour
object.strftime(format)
end
-
+
+ def initialized?
+ @initialized ||= false
+ end
+
protected
-
+
def init_translations
load_translations(*I18n.load_path)
@initialized = true
end
-
+
def translations
@translations ||= {}
end
-
- # Looks up a translation from the translations hash. Returns nil if
+
+ # Looks up a translation from the translations hash. Returns nil if
# eiher key is nil, or locale, scope or key do not exist as a key in the
# nested translations hash. Splits keys or scopes containing dots
# into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as
# <tt>%w(currency format)</tt>.
def lookup(locale, key, scope = [])
return unless key
- init_translations unless @initialized
+ init_translations unless initialized?
keys = I18n.send :normalize_translation_keys, locale, key, scope
- keys.inject(translations){|result, k| result[k.to_sym] or return nil }
+ keys.inject(translations) do |result, k|
+ if (x = result[k.to_sym]).nil?
+ return nil
+ else
+ x
+ end
+ end
end
-
- # Evaluates a default translation.
+
+ # Evaluates a default translation.
# If the given default is a String it is used literally. If it is a Symbol
# it will be translated with the given options. If it is an Array the first
# translation yielded will be returned.
- #
- # <em>I.e.</em>, <tt>default(locale, [:foo, 'default'])</tt> will return +default+ if
+ #
+ # <em>I.e.</em>, <tt>default(locale, [:foo, 'default'])</tt> will return +default+ if
# <tt>translate(locale, :foo)</tt> does not yield a result.
def default(locale, default, options = {})
case default
when String then default
when Symbol then translate locale, default, options
- when Array then default.each do |obj|
+ when Array then default.each do |obj|
result = default(locale, obj, options.dup) and return result
end and nil
end
rescue MissingTranslationData
nil
end
-
+
# Picks a translation from an array according to English pluralization
# rules. It will pick the first translation if count is not equal to 1
# and the second translation if it is equal to 1. Other backends can
@@ -113,20 +129,18 @@ def pluralize(locale, entry, count)
raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key)
entry[key]
end
-
+
# Interpolates values into a given string.
- #
- # interpolate "file {{file}} opened by \\{{user}}", :file => 'test.txt', :user => 'Mr. X'
+ #
+ # interpolate "file {{file}} opened by \\{{user}}", :file => 'test.txt', :user => 'Mr. X'
# # => "file test.txt opened by {{user}}"
- #
+ #
# Note that you have to double escape the <tt>\\</tt> when you want to escape
# the <tt>{{...}}</tt> key in a string (once for the string and once for the
# interpolation).
def interpolate(locale, string, values = {})
return string unless string.is_a?(String)
- string = string.gsub(/%d/, '{{count}}').gsub(/%s/, '{{value}}')
-
if string.respond_to?(:force_encoding)
original_encoding = string.encoding
string.force_encoding(Encoding::BINARY)
@@ -149,8 +163,8 @@ def interpolate(locale, string, values = {})
result.force_encoding(original_encoding) if original_encoding
result
end
-
- # Loads a single translations file by delegating to #load_rb or
+
+ # Loads a single translations file by delegating to #load_rb or
# #load_yml depending on the file extension and directly merges the
# data to the existing translations. Raises I18n::UnknownFileType
# for all other file extensions.
@@ -160,19 +174,19 @@ def load_file(filename)
data = send :"load_#{type}", filename # TODO raise a meaningful exception if this does not yield a Hash
data.each{|locale, d| merge_translations locale, d }
end
-
+
# Loads a plain Ruby translations file. eval'ing the file must yield
# a Hash containing translation data with locales as toplevel keys.
def load_rb(filename)
eval IO.read(filename), binding, filename
end
-
- # Loads a YAML translations file. The data must have locales as
+
+ # Loads a YAML translations file. The data must have locales as
# toplevel keys.
def load_yml(filename)
YAML::load IO.read(filename)
end
-
+
# Deep merges the given translations hash with the existing translations
# for the given locale
def merge_translations(locale, data)
@@ -184,7 +198,7 @@ def merge_translations(locale, data)
merger = proc{|key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
translations[locale].merge! data, &merger
end
-
+
# Return a new hash with all keys and nested keys converted to symbols.
def deep_symbolize_keys(hash)
hash.inject({}){|result, (key, value)|
View
6 lib/i18n/exceptions.rb
@@ -1,6 +1,6 @@
module I18n
class ArgumentError < ::ArgumentError; end
-
+
class InvalidLocale < ArgumentError
attr_reader :locale
def initialize(locale)
@@ -42,12 +42,12 @@ def initialize(key, string)
super "reserved key #{key.inspect} used in #{string.inspect}"
end
end
-
+
class UnknownFileType < ArgumentError
attr_reader :type, :filename
def initialize(type, filename)
@type, @filename = type, filename
super "can not load translations from #{filename}, the file type #{type} is not known"
end
end
-end
+end
View
2 test/all.rb
@@ -2,4 +2,4 @@
require dir + '/i18n_test.rb'
require dir + '/simple_backend_test.rb'
require dir + '/i18n_exceptions_test.rb'
-# require dir + '/custom_backend_test.rb'
+# *require* dir + '/custom_backend_test.rb'
View
28 test/i18n_exceptions_test.rb
@@ -12,13 +12,13 @@ def test_invalid_locale_stores_locale
rescue I18n::ArgumentError => e
assert_nil e.locale
end
-
+
def test_invalid_locale_message
force_invalid_locale
rescue I18n::ArgumentError => e
assert_equal 'nil is not a valid locale', e.message
end
-
+
def test_missing_translation_data_stores_locale_key_and_options
force_missing_translation_data
rescue I18n::ArgumentError => e
@@ -27,72 +27,72 @@ def test_missing_translation_data_stores_locale_key_and_options
assert_equal :foo, e.key
assert_equal options, e.options
end
-
+
def test_missing_translation_data_message
force_missing_translation_data
rescue I18n::ArgumentError => e
assert_equal 'translation missing: de-DE, bar, foo', e.message
end
-
+
def test_invalid_pluralization_data_stores_entry_and_count
force_invalid_pluralization_data
rescue I18n::ArgumentError => e
assert_equal [:bar], e.entry
assert_equal 1, e.count
end
-
+
def test_invalid_pluralization_data_message
force_invalid_pluralization_data
rescue I18n::ArgumentError => e
assert_equal 'translation data [:bar] can not be used with :count => 1', e.message
end
-
+
def test_missing_interpolation_argument_stores_key_and_string
force_missing_interpolation_argument
rescue I18n::ArgumentError => e
assert_equal 'bar', e.key
assert_equal "{{bar}}", e.string
end
-
+
def test_missing_interpolation_argument_message
force_missing_interpolation_argument
rescue I18n::ArgumentError => e
assert_equal 'interpolation argument bar missing in "{{bar}}"', e.message
end
-
+
def test_reserved_interpolation_key_stores_key_and_string
force_reserved_interpolation_key
rescue I18n::ArgumentError => e
assert_equal 'scope', e.key
assert_equal "{{scope}}", e.string
end
-
+
def test_reserved_interpolation_key_message
force_reserved_interpolation_key
rescue I18n::ArgumentError => e
assert_equal 'reserved key "scope" used in "{{scope}}"', e.message
end
-
+
private
def force_invalid_locale
I18n.backend.translate nil, :foo
end
-
+
def force_missing_translation_data
I18n.backend.store_translations 'de-DE', :bar => nil
I18n.backend.translate 'de-DE', :foo, :scope => :bar
end
-
+
def force_invalid_pluralization_data
I18n.backend.store_translations 'de-DE', :foo => [:bar]
I18n.backend.translate 'de-DE', :foo, :count => 1
end
-
+
def force_missing_interpolation_argument
I18n.backend.store_translations 'de-DE', :foo => "{{bar}}"
I18n.backend.translate 'de-DE', :foo, :baz => 'baz'
end
-
+
def force_reserved_interpolation_key
I18n.backend.store_translations 'de-DE', :foo => "{{scope}}"
I18n.backend.translate 'de-DE', :foo, :baz => 'baz'
View
46 test/i18n_test.rb
@@ -17,108 +17,108 @@ def setup
}
}
end
-
+
def test_uses_simple_backend_set_by_default
assert I18n.backend.is_a?(I18n::Backend::Simple)
end
-
+
def test_can_set_backend
assert_nothing_raised{ I18n.backend = self }
assert_equal self, I18n.backend
I18n.backend = I18n::Backend::Simple.new
end
-
+
def test_uses_en_us_as_default_locale_by_default
assert_equal 'en-US', I18n.default_locale
end
-
+
def test_can_set_default_locale
assert_nothing_raised{ I18n.default_locale = 'de-DE' }
assert_equal 'de-DE', I18n.default_locale
I18n.default_locale = 'en-US'
end
-
+
def test_uses_default_locale_as_locale_by_default
assert_equal I18n.default_locale, I18n.locale
end
-
+
def test_can_set_locale_to_thread_current
assert_nothing_raised{ I18n.locale = 'de-DE' }
assert_equal 'de-DE', I18n.locale
assert_equal 'de-DE', Thread.current[:locale]
I18n.locale = 'en-US'
end
-
+
def test_can_set_exception_handler
assert_nothing_raised{ I18n.exception_handler = :custom_exception_handler }
I18n.exception_handler = :default_exception_handler # revert it
end
-
+
def test_uses_custom_exception_handler
I18n.exception_handler = :custom_exception_handler
I18n.expects(:custom_exception_handler)
I18n.translate :bogus
I18n.exception_handler = :default_exception_handler # revert it
end
-
+
def test_delegates_translate_to_backend
I18n.backend.expects(:translate).with 'de-DE', :foo, {}
I18n.translate :foo, :locale => 'de-DE'
end
-
+
def test_delegates_localize_to_backend
I18n.backend.expects(:localize).with 'de-DE', :whatever, :default
I18n.localize :whatever, :locale => 'de-DE'
end
-
+
def test_translate_given_no_locale_uses_i18n_locale
I18n.backend.expects(:translate).with 'en-US', :foo, {}
I18n.translate :foo
- end
-
+ end
+
def test_translate_on_nested_symbol_keys_works
assert_equal ".", I18n.t(:'currency.format.separator')
end
-
+
def test_translate_with_nested_string_keys_works
assert_equal ".", I18n.t('currency.format.separator')
end
-
+
def test_translate_with_array_as_scope_works
assert_equal ".", I18n.t(:separator, :scope => ['currency.format'])
end
-
+
def test_translate_with_array_containing_dot_separated_strings_as_scope_works
assert_equal ".", I18n.t(:separator, :scope => ['currency.format'])
end
-
+
def test_translate_with_key_array_and_dot_separated_scope_works
assert_equal [".", ","], I18n.t(%w(separator delimiter), :scope => 'currency.format')
end
-
+
def test_translate_with_dot_separated_key_array_and_scope_works
assert_equal [".", ","], I18n.t(%w(format.separator format.delimiter), :scope => 'currency')
end
-
+
def test_translate_with_options_using_scope_works
I18n.backend.expects(:translate).with('de-DE', :precision, :scope => :"currency.format")
I18n.with_options :locale => 'de-DE', :scope => :'currency.format' do |locale|
locale.t :precision
end
end
-
+
# def test_translate_given_no_args_raises_missing_translation_data
# assert_equal "translation missing: en-US, no key", I18n.t
# end
-
+
def test_translate_given_a_bogus_key_raises_missing_translation_data
assert_equal "translation missing: en-US, bogus", I18n.t(:bogus)
end
-
+
def test_localize_nil_raises_argument_error
assert_raises(I18n::ArgumentError) { I18n.l nil }
end
-
+
def test_localize_object_raises_argument_error
assert_raises(I18n::ArgumentError) { I18n.l Object.new }
end
View
184 test/simple_backend_test.rb
@@ -16,16 +16,16 @@ def setup_backend
@locale_dir = File.dirname(__FILE__) + '/locale'
end
alias :setup :setup_backend
-
+
# def backend_reset_translations!
# I18n::Backend::Simple::ClassMethods.send :class_variable_set, :@@translations, {}
# end
def backend_get_translations
# I18n::Backend::Simple::ClassMethods.send :class_variable_get, :@@translations
@backend.instance_variable_get :@translations
- end
-
+ end
+
def add_datetime_translations
@backend.store_translations :'de-DE', {
:date => {
@@ -53,188 +53,188 @@ def add_datetime_translations
:distance_in_words => {
:half_a_minute => 'half a minute',
:less_than_x_seconds => {
- :one => 'less than 1 second',
+ :one => 'less than 1 second',
:other => 'less than {{count}} seconds'
},
:x_seconds => {
- :one => '1 second',
+ :one => '1 second',
:other => '{{count}} seconds'
},
:less_than_x_minutes => {
- :one => 'less than a minute',
+ :one => 'less than a minute',
:other => 'less than {{count}} minutes'
},
:x_minutes => {
- :one => '1 minute',
+ :one => '1 minute',
:other => '{{count}} minutes'
},
:about_x_hours => {
- :one => 'about 1 hour',
+ :one => 'about 1 hour',
:other => 'about {{count}} hours'
},
:x_days => {
:one => '1 day',
- :other => '{{count}} days'
+ :other => '{{count}} days'
},
- :about_x_months => {
- :one => 'about 1 month',
+ :about_x_months => {
+ :one => 'about 1 month',
:other => 'about {{count}} months'
},
:x_months => {
- :one => '1 month',
+ :one => '1 month',
:other => '{{count}} months'
},
:about_x_years => {
- :one => 'about 1 year',
+ :one => 'about 1 year',
:other => 'about {{count}} year'
},
:over_x_years => {
- :one => 'over 1 year',
+ :one => 'over 1 year',
:other => 'over {{count}} years'
}
}
- }
+ }
}
end
end
class I18nSimpleBackendTranslationsTest < Test::Unit::TestCase
include I18nSimpleBackendTestSetup
-
+
def test_store_translations_adds_translations # no, really :-)
@backend.store_translations :'en-US', :foo => 'bar'
assert_equal Hash[:'en-US', {:foo => 'bar'}], backend_get_translations
end
-
+
def test_store_translations_deep_merges_translations
@backend.store_translations :'en-US', :foo => {:bar => 'bar'}
@backend.store_translations :'en-US', :foo => {:baz => 'baz'}
assert_equal Hash[:'en-US', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations
end
-
+
def test_store_translations_forces_locale_to_sym
@backend.store_translations 'en-US', :foo => 'bar'
assert_equal Hash[:'en-US', {:foo => 'bar'}], backend_get_translations
end
-
+
def test_store_translations_converts_keys_to_symbols
# backend_reset_translations!
@backend.store_translations 'en-US', 'foo' => {'bar' => 'bar', 'baz' => 'baz'}
- assert_equal Hash[:'en-US', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations
+ assert_equal Hash[:'en-US', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations
end
end
-
+
class I18nSimpleBackendTranslateTest < Test::Unit::TestCase
include I18nSimpleBackendTestSetup
def test_translate_calls_lookup_with_locale_given
@backend.expects(:lookup).with('de-DE', :bar, [:foo]).returns 'bar'
@backend.translate 'de-DE', :bar, :scope => [:foo]
end
-
+
def test_given_no_keys_it_returns_the_default
- assert_equal 'default', @backend.translate('en-US', nil, :default => 'default')
+ assert_equal 'default', @backend.translate('en-US', nil, :default => 'default')
end
-
+
def test_translate_given_a_symbol_as_a_default_translates_the_symbol
assert_equal 'bar', @backend.translate('en-US', nil, :scope => [:foo], :default => :bar)
end
-
+
def test_translate_given_an_array_as_default_uses_the_first_match
assert_equal 'bar', @backend.translate('en-US', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :bar])
end
-
+
def test_translate_given_an_array_of_inexistent_keys_it_raises_missing_translation_data
- assert_raises I18n::MissingTranslationData do
+ assert_raises I18n::MissingTranslationData do
@backend.translate('en-US', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :does_not_exist_3])
end
end
-
+
def test_translate_an_array_of_keys_translates_all_of_them
assert_equal %w(bar baz), @backend.translate('en-US', [:bar, :baz], :scope => [:foo])
end
-
+
def test_translate_calls_pluralize
@backend.expects(:pluralize).with 'en-US', 'bar', 1
@backend.translate 'en-US', :bar, :scope => [:foo], :count => 1
end
-
+
def test_translate_calls_interpolate
@backend.expects(:interpolate).with 'en-US', 'bar', {}
@backend.translate 'en-US', :bar, :scope => [:foo]
end
-
+
def test_translate_calls_interpolate_including_count_as_a_value
@backend.expects(:interpolate).with 'en-US', 'bar', {:count => 1}
@backend.translate 'en-US', :bar, :scope => [:foo], :count => 1
end
-
+
def test_translate_given_nil_as_a_locale_raises_an_argument_error
assert_raises(I18n::InvalidLocale){ @backend.translate nil, :bar }
end
-
+
def test_translate_with_a_bogus_key_and_no_default_raises_missing_translation_data
assert_raises(I18n::MissingTranslationData){ @backend.translate 'de-DE', :bogus }
end
end
-
+
class I18nSimpleBackendLookupTest < Test::Unit::TestCase
include I18nSimpleBackendTestSetup
-
+
# useful because this way we can use the backend with no key for interpolation/pluralization
- def test_lookup_given_nil_as_a_key_returns_nil
+ def test_lookup_given_nil_as_a_key_returns_nil
assert_nil @backend.send(:lookup, 'en-US', nil)
end
-
+
def test_lookup_given_nested_keys_looks_up_a_nested_hash_value
assert_equal 'bar', @backend.send(:lookup, 'en-US', :bar, [:foo])
end
end
-
+
class I18nSimpleBackendPluralizeTest < Test::Unit::TestCase
include I18nSimpleBackendTestSetup
-
+
def test_pluralize_given_nil_returns_the_given_entry
entry = {:one => 'bar', :other => 'bars'}
assert_equal entry, @backend.send(:pluralize, nil, entry, nil)
end
-
+
def test_pluralize_given_0_returns_zero_string_if_zero_key_given
assert_equal 'zero', @backend.send(:pluralize, nil, {:zero => 'zero', :one => 'bar', :other => 'bars'}, 0)
end
-
+
def test_pluralize_given_0_returns_plural_string_if_no_zero_key_given
assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 0)
end
-
+
def test_pluralize_given_1_returns_singular_string
assert_equal 'bar', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 1)
end
-
+
def test_pluralize_given_2_returns_plural_string
assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 2)
end
-
+
def test_pluralize_given_3_returns_plural_string
assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 3)
end
-
+
def test_interpolate_given_incomplete_pluralization_data_raises_invalid_pluralization_data
assert_raises(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, {:one => 'bar'}, 2) }
end
-
+
# def test_interpolate_given_a_string_raises_invalid_pluralization_data
# assert_raises(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, 'bar', 2) }
# end
- #
+ #
# def test_interpolate_given_an_array_raises_invalid_pluralization_data
# assert_raises(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, ['bar'], 2) }
# end
end
-
+
class I18nSimpleBackendInterpolateTest < Test::Unit::TestCase
include I18nSimpleBackendTestSetup
-
+
def test_interpolate_given_a_value_hash_interpolates_the_values_to_the_string
assert_equal 'Hi David!', @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => 'David')
end
@@ -246,183 +246,183 @@ def test_interpolate_given_a_value_hash_interpolates_into_unicode_string
def test_interpolate_given_nil_as_a_string_returns_nil
assert_nil @backend.send(:interpolate, nil, nil, :name => 'David')
end
-
+
def test_interpolate_given_an_non_string_as_a_string_returns_nil
assert_equal [], @backend.send(:interpolate, nil, [], :name => 'David')
end
-
+
def test_interpolate_given_a_values_hash_with_nil_values_interpolates_the_string
assert_equal 'Hi !', @backend.send(:interpolate, nil, 'Hi {{name}}!', {:name => nil})
end
-
+
def test_interpolate_given_an_empty_values_hash_raises_missing_interpolation_argument
assert_raises(I18n::MissingInterpolationArgument) { @backend.send(:interpolate, nil, 'Hi {{name}}!', {}) }
end
-
+
def test_interpolate_given_a_string_containing_a_reserved_key_raises_reserved_interpolation_key
assert_raises(I18n::ReservedInterpolationKey) { @backend.send(:interpolate, nil, '{{default}}', {:default => nil}) }
end
end
class I18nSimpleBackendLocalizeDateTest < Test::Unit::TestCase
include I18nSimpleBackendTestSetup
-
+
def setup
@backend = I18n::Backend::Simple.new
add_datetime_translations
@date = Date.new 2008, 1, 1
end
-
+
def test_translate_given_the_short_format_it_uses_it
assert_equal '01. Jan', @backend.localize('de-DE', @date, :short)
end
-
+
def test_translate_given_the_long_format_it_uses_it
assert_equal '01. Januar 2008', @backend.localize('de-DE', @date, :long)
end
-
+
def test_translate_given_the_default_format_it_uses_it
assert_equal '01.01.2008', @backend.localize('de-DE', @date, :default)
end
-
+
def test_translate_given_a_day_name_format_it_returns_a_day_name
assert_equal 'Dienstag', @backend.localize('de-DE', @date, '%A')
end
-
+
def test_translate_given_an_abbr_day_name_format_it_returns_an_abbrevated_day_name
assert_equal 'Di', @backend.localize('de-DE', @date, '%a')
end
-
+
def test_translate_given_a_month_name_format_it_returns_a_month_name
assert_equal 'Januar', @backend.localize('de-DE', @date, '%B')
end
-
+
def test_translate_given_an_abbr_month_name_format_it_returns_an_abbrevated_month_name
assert_equal 'Jan', @backend.localize('de-DE', @date, '%b')
end
-
+
def test_translate_given_no_format_it_does_not_fail
assert_nothing_raised{ @backend.localize 'de-DE', @date }
end
-
+
def test_translate_given_an_unknown_format_it_does_not_fail
assert_nothing_raised{ @backend.localize 'de-DE', @date, '%x' }
- end
-
+ end
+
def test_localize_nil_raises_argument_error
assert_raises(I18n::ArgumentError) { @backend.localize 'de-DE', nil }
end
-
+
def test_localize_object_raises_argument_error
assert_raises(I18n::ArgumentError) { @backend.localize 'de-DE', Object.new }
end
end
class I18nSimpleBackendLocalizeDateTimeTest < Test::Unit::TestCase
include I18nSimpleBackendTestSetup
-
+
def setup
@backend = I18n::Backend::Simple.new
add_datetime_translations
@morning = DateTime.new 2008, 1, 1, 6
@evening = DateTime.new 2008, 1, 1, 18
end
-
+
def test_translate_given_the_short_format_it_uses_it
assert_equal '01. Jan 06:00', @backend.localize('de-DE', @morning, :short)
end
-
+
def test_translate_given_the_long_format_it_uses_it
assert_equal '01. Januar 2008 06:00', @backend.localize('de-DE', @morning, :long)
end
-
+
def test_translate_given_the_default_format_it_uses_it
assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de-DE', @morning, :default)
end
-
+
def test_translate_given_a_day_name_format_it_returns_the_correct_day_name
assert_equal 'Dienstag', @backend.localize('de-DE', @morning, '%A')
end
-
+
def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name
assert_equal 'Di', @backend.localize('de-DE', @morning, '%a')
end
-
+
def test_translate_given_a_month_name_format_it_returns_the_correct_month_name
assert_equal 'Januar', @backend.localize('de-DE', @morning, '%B')
end
-
+
def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name
assert_equal 'Jan', @backend.localize('de-DE', @morning, '%b')
end
-
+
def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator
assert_equal 'am', @backend.localize('de-DE', @morning, '%p')
assert_equal 'pm', @backend.localize('de-DE', @evening, '%p')
end
-
+
def test_translate_given_no_format_it_does_not_fail
assert_nothing_raised{ @backend.localize 'de-DE', @morning }
end
-
+
def test_translate_given_an_unknown_format_it_does_not_fail
assert_nothing_raised{ @backend.localize 'de-DE', @morning, '%x' }
- end
+ end
end
class I18nSimpleBackendLocalizeTimeTest < Test::Unit::TestCase
include I18nSimpleBackendTestSetup
-
+
def setup
@old_timezone, ENV['TZ'] = ENV['TZ'], 'UTC'
@backend = I18n::Backend::Simple.new
add_datetime_translations
@morning = Time.parse '2008-01-01 6:00 UTC'
@evening = Time.parse '2008-01-01 18:00 UTC'
end
-
+
def teardown
@old_timezone ? ENV['TZ'] = @old_timezone : ENV.delete('TZ')
end
-
+
def test_translate_given_the_short_format_it_uses_it
assert_equal '01. Jan 06:00', @backend.localize('de-DE', @morning, :short)
end
-
+
def test_translate_given_the_long_format_it_uses_it
assert_equal '01. Januar 2008 06:00', @backend.localize('de-DE', @morning, :long)
end
-
+
# TODO Seems to break on Windows because ENV['TZ'] is ignored. What's a better way to do this?
# def test_translate_given_the_default_format_it_uses_it
# assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de-DE', @morning, :default)
# end
-
+
def test_translate_given_a_day_name_format_it_returns_the_correct_day_name
assert_equal 'Dienstag', @backend.localize('de-DE', @morning, '%A')
end
-
+
def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name
assert_equal 'Di', @backend.localize('de-DE', @morning, '%a')
end
-
+
def test_translate_given_a_month_name_format_it_returns_the_correct_month_name
assert_equal 'Januar', @backend.localize('de-DE', @morning, '%B')
end
-
+
def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name
assert_equal 'Jan', @backend.localize('de-DE', @morning, '%b')
end
-
+
def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator
assert_equal 'am', @backend.localize('de-DE', @morning, '%p')
assert_equal 'pm', @backend.localize('de-DE', @evening, '%p')
end
-
+
def test_translate_given_no_format_it_does_not_fail
assert_nothing_raised{ @backend.localize 'de-DE', @morning }
end
-
+
def test_translate_given_an_unknown_format_it_does_not_fail
assert_nothing_raised{ @backend.localize 'de-DE', @morning, '%x' }
end
@@ -432,7 +432,7 @@ class I18nSimpleBackendHelperMethodsTest < Test::Unit::TestCase
def setup
@backend = I18n::Backend::Simple.new
end
-
+
def test_deep_symbolize_keys_works
result = @backend.send :deep_symbolize_keys, 'foo' => {'bar' => {'baz' => 'bar'}}
expected = {:foo => {:bar => {:baz => 'bar'}}}
@@ -460,7 +460,7 @@ def test_load_rb_loads_data_from_yaml_file
data = @backend.send :load_yml, "#{@locale_dir}/en-US.yml"
assert_equal({'en-US-Yaml' => {'foo' => {'bar' => 'baz'}}}, data)
end
-
+
def test_load_translations_loads_from_different_file_formats
@backend = I18n::Backend::Simple.new
@backend.load_translations "#{@locale_dir}/en-US.rb", "#{@locale_dir}/en-US.yml"

0 comments on commit 39d9a47

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