diff options
author | David Chelimsky <dchelimsky@gmail.com> | 2013-08-28 05:07:18 +0200 |
---|---|---|
committer | David Chelimsky <dchelimsky@gmail.com> | 2013-09-11 15:28:38 +0200 |
commit | b16b08ebde636dd530afeeb00ca32f6d49fda819 (patch) | |
tree | 3e65b000939fe8e50d3e5df772ddbf4e868faec5 /activesupport/lib | |
parent | 744ed5c39381cb3e58eba6fab21f42b3408dce53 (diff) | |
download | rails-b16b08ebde636dd530afeeb00ca32f6d49fda819.tar.gz rails-b16b08ebde636dd530afeeb00ca32f6d49fda819.tar.bz2 rails-b16b08ebde636dd530afeeb00ca32f6d49fda819.zip |
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
Diffstat (limited to 'activesupport/lib')
-rw-r--r-- | activesupport/lib/active_support/duration.rb | 10 |
1 files changed, 4 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 |