diff options
author | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2013-09-11 14:58:46 -0700 |
---|---|---|
committer | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2013-09-11 14:58:46 -0700 |
commit | bca623bc5342007216ec9757c5192fef455e8a65 (patch) | |
tree | ecb6c520d9b8df8ac8aee09f0d95b9d06bb96fd0 /activesupport | |
parent | 1fa76a2f3de5276001afe5d6815136680f7a87de (diff) | |
parent | b16b08ebde636dd530afeeb00ca32f6d49fda819 (diff) | |
download | rails-bca623bc5342007216ec9757c5192fef455e8a65.tar.gz rails-bca623bc5342007216ec9757c5192fef455e8a65.tar.bz2 rails-bca623bc5342007216ec9757c5192fef455e8a65.zip |
Merge pull request #12200 from dchelimsky/simplify-duration-inspect-even-more
Reduce Duration#inspect to a single series of transformations
Diffstat (limited to 'activesupport')
-rw-r--r-- | activesupport/lib/active_support/duration.rb | 10 | ||||
-rw-r--r-- | activesupport/test/core_ext/duration_test.rb | 3 |
2 files changed, 7 insertions, 6 deletions
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb index 00727ef73c..87b6407038 100644 --- a/activesupport/lib/active_support/duration.rb +++ b/activesupport/lib/active_support/duration.rb @@ -70,12 +70,10 @@ module ActiveSupport 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 diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index 5e3987265b..ed267cf4b9 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -27,6 +27,7 @@ class DurationTest < ActiveSupport::TestCase 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 @@ class DurationTest < ActiveSupport::TestCase 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 |