Permalink
Browse files

Move exists? implementation to Backend::Base, and Backend::Chain. Add…

…ed test to lib/i18n/tests/basics.rb
  • Loading branch information...
1 parent 93aba7a commit 2e12adb60a39ca00c3854098f7d3a9a1f9167d67 @ndbroadbent ndbroadbent committed Dec 18, 2012
Showing with 21 additions and 5 deletions.
  1. +6 −5 lib/i18n.rb
  2. +4 −0 lib/i18n/backend/base.rb
  3. +6 −0 lib/i18n/backend/chain.rb
  4. +5 −0 lib/i18n/tests/basics.rb
View
@@ -167,6 +167,12 @@ def translate!(key, options={})
end
alias :t! :translate!
+ # Returns true if a translation exists for a given key, otherwise returns false.
+ def exists?(key, locale = config.locale)
+ raise I18n::ArgumentError if key.is_a?(String) && key.empty?
+ config.backend.exists?(locale, key)
+ end
+
# Transliterates UTF-8 characters to ASCII. By default this method will
# transliterate only Latin strings to an ASCII approximation:
#
@@ -229,11 +235,6 @@ def transliterate(*args)
handle_exception(handling, exception, locale, key, options || {})
end
- # Checks if a certain key exists in the translations
- def exists?(key, locale = locale)
- config.backend.send(:lookup, locale, key).present?
- end
-
# Localizes certain objects, such as dates and numbers to local formatting.
def localize(object, options = nil)
options = options ? options.dup : {}
View
@@ -42,6 +42,10 @@ def translate(locale, key, options = {})
entry
end
+ def exists?(locale, key)
+ lookup(locale, key) != nil
+ end
+
# Acts the same as +strftime+, but uses a localized version of the
# format 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>).
@@ -56,6 +56,12 @@ def translate(locale, key, default_options = {})
throw(:exception, I18n::MissingTranslation.new(locale, key, options))
end
+ def exists?(locale, key)
+ backends.any? do |backend|
+ backend.exists?(locale, key)
+ end
+ end
+
def localize(locale, object, format = :default, options = {})
backends.each do |backend|
catch(:exception) do
View
@@ -41,6 +41,11 @@ def teardown
assert_equal I18n.available_locales, I18n.available_locales
end
+ test "exists? is implemented by the backend" do
+ I18n.backend.store_translations(:foo, :bar => 'baz')
+ assert I18n.exists?(:bar, :foo)
+ end
+
test "storing a nil value as a translation removes it from the available locale data" do
I18n.backend.store_translations(:en, :to_be_deleted => 'bar')
assert_equal 'bar', I18n.t(:to_be_deleted, :default => 'baz')

0 comments on commit 2e12adb

Please sign in to comment.