提交 b16b08eb 编写于 作者: D David Chelimsky

Reduce Duration#inspect to a single series of transformations

* eliminates need for temp Hash

Also added a couple of examples to DurationTest to specify:

* duration can be defined with units out of order e.g.
  1.month + 1.year + 1.second + 1.day
* equality with a Fixnum works regardless of which operand is on which
  side of the operator
上级 744ed5c3
......@@ -70,12 +70,10 @@ def ago(time = ::Time.current)
alias :until :ago
def inspect #:nodoc:
val_for = parts.inject(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }
[:years, :months, :days, :minutes, :seconds].
select {|unit| val_for[unit].nonzero?}.
tap {|units| units << :seconds if units.empty?}.
map {|unit| [unit, val_for[unit]]}.
map {|unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}"}.
parts.
reduce(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }.
sort_by {|unit, _ | [:years, :months, :days, :minutes, :seconds].index(unit)}.
map {|unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}"}.
to_sentence(:locale => :en)
end
......
......@@ -27,6 +27,7 @@ def test_threequals
def test_equals
assert 1.day == 1.day
assert 1.day == 1.day.to_i
assert 1.day.to_i == 1.day
assert !(1.day == 'foo')
end
......@@ -37,6 +38,8 @@ def test_inspect
assert_equal '6 months and -2 days', (6.months - 2.days).inspect
assert_equal '10 seconds', 10.seconds.inspect
assert_equal '10 years, 2 months, and 1 day', (10.years + 2.months + 1.day).inspect
assert_equal '10 years, 2 months, and 1 day', (10.years + 1.month + 1.day + 1.month).inspect
assert_equal '10 years, 2 months, and 1 day', (1.day + 10.years + 2.months).inspect
assert_equal '7 days', 1.week.inspect
assert_equal '14 days', 1.fortnight.inspect
end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册