Permalink
Browse files

Merge pull request #11856 from dchelimsky/refactor-duration-inspect

Refactor Duration#inspect
  • Loading branch information...
2 parents f948814 + af3ea54 commit 1577d9661a9ee0268d9f101c6c7f6435a87e8de0 @steveklabnik steveklabnik committed Aug 12, 2013
Showing with 7 additions and 7 deletions.
  1. +7 −7 activesupport/lib/active_support/duration.rb
@@ -70,13 +70,13 @@ def ago(time = ::Time.current)
alias :until :ago
def inspect #:nodoc:
- consolidated = parts.inject(::Hash.new(0)) { |h,(l,r)| h[l] += r; h }
- parts = [:years, :months, :days, :minutes, :seconds].map do |length|
- n = consolidated[length]
- "#{n} #{n == 1 ? length.to_s.chop : length.to_s}" if n.nonzero?
- end.compact
- parts = ["0 seconds"] if parts.empty?
- parts.to_sentence(:locale => :en)
+ 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}"}.
+ to_sentence(:locale => :en)
end
def as_json(options = nil) #:nodoc:

0 comments on commit 1577d96

Please sign in to comment.