Skip to content

Commit

Permalink
Merge pull request #11856 from dchelimsky/refactor-duration-inspect
Browse files Browse the repository at this point in the history
Refactor Duration#inspect
  • Loading branch information
steveklabnik committed Aug 12, 2013
2 parents f948814 + af3ea54 commit 1577d96
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions activesupport/lib/active_support/duration.rb
Expand Up @@ -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:
Expand Down

0 comments on commit 1577d96

Please sign in to comment.