Skip to content

Commit

Permalink
Added :default param for I18n.localize
Browse files Browse the repository at this point in the history
Fixes #251
  • Loading branch information
fengb authored and radar committed Nov 17, 2016
1 parent 6f291c4 commit 72303d9
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/i18n/backend/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ def exists?(locale, key)
# 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>).
def localize(locale, object, format = :default, options = {})
if object.nil? && options.include?(:default)
return options[:default]
end
raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime)

if Symbol === format
Expand Down
4 changes: 4 additions & 0 deletions lib/i18n/tests/localization/date.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ def setup
assert_nothing_raised { I18n.l(@date, options.freeze) }
end

test "localize Date: given nil with default value it returns default" do
assert_equal 'default', I18n.l(nil, :default => 'default')
end

test "localize Date: given nil it raises I18n::ArgumentError" do
assert_raise(I18n::ArgumentError) { I18n.l(nil) }
end
Expand Down
4 changes: 4 additions & 0 deletions test/i18n_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,10 @@ def setup
assert_raise(I18n::ArgumentError) { I18n.l nil }
end

test "localize given nil and default returns default" do
assert_equal nil, I18n.l(nil, :default => nil)
end

test "localize given an Object raises an I18n::ArgumentError" do
assert_raise(I18n::ArgumentError) { I18n.l Object.new }
end
Expand Down

0 comments on commit 72303d9

Please sign in to comment.