lib/active_support/duration.rb in activesupport-5.2.8.1 vs lib/active_support/duration.rb in activesupport-6.0.0.beta1
- old
+ new
@@ -181,19 +181,19 @@
# ActiveSupport::Duration.build(31556952).parts # => {:years=>1}
# ActiveSupport::Duration.build(2716146).parts # => {:months=>1, :days=>1}
#
def build(value)
parts = {}
- remainder = value.round(9)
+ remainder = value.to_f
PARTS.each do |part|
unless part == :seconds
part_in_seconds = PARTS_IN_SECONDS[part]
parts[part] = remainder.div(part_in_seconds)
- remainder %= part_in_seconds
+ remainder = (remainder % part_in_seconds).round(9)
end
- end unless value == 0
+ end
parts[:seconds] = remainder
new(value, parts)
end
@@ -208,16 +208,19 @@
end
def initialize(value, parts) #:nodoc:
@value, @parts = value, parts.to_h
@parts.default = 0
- @parts.reject! { |k, v| v.zero? } unless value == 0
+ @parts.reject! { |k, v| v.zero? }
end
def coerce(other) #:nodoc:
- if Scalar === other
+ case other
+ when Scalar
[other, self]
+ when Duration
+ [Scalar.new(other.value), self]
else
[Scalar.new(other), self]
end
end
@@ -371,11 +374,10 @@
def inspect #:nodoc:
return "0 seconds" if parts.empty?
parts.
- reduce(::Hash.new(0)) { |h, (l, r)| h[l] += r; h }.
sort_by { |unit, _ | PARTS.index(unit) }.
map { |unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}" }.
to_sentence(locale: ::I18n.default_locale)
end
@@ -398,26 +400,22 @@
end
private
def sum(sign, time = ::Time.current)
- unless time.acts_like?(:time) || time.acts_like?(:date)
- raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
- end
-
- if parts.empty?
- time.since(sign * value)
- else
- parts.inject(time) do |t, (type, number)|
+ parts.inject(time) do |t, (type, number)|
+ if t.acts_like?(:time) || t.acts_like?(:date)
if type == :seconds
t.since(sign * number)
elsif type == :minutes
t.since(sign * number * 60)
elsif type == :hours
t.since(sign * number * 3600)
else
t.advance(type => sign * number)
end
+ else
+ raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
end
end
end
def respond_to_missing?(method, _)