класс ActiveSupport::Duration
Обеспечивает точные измерения дат и времени с использованием Date#advance и Time#advance, соответственно. В основном поддерживает методы для Numeric.
1.month.ago # equivalent to Time.now.advance(months: -1)
Константы
- PARTS
- PARTS_IN_SECONDS
- СЕКУНДЫ_В_СУТКАХ
- СЕКУНДЫ_В_ЧАСЕ
- СЕКУНДЫ_В_МИНУТЕ
- СЕКУНДЫ_В_МЕСЯЦЕ
- СЕКУНДЫ_В_НЕДЕЛЕ
- СЕКУНДЫ_В_ГОДУ
- ПЕРЕМЕННЫЕ_ЧАСТИ
Атрибуты
Публичные методы класса
# File activesupport/lib/active_support/duration.rb, line 188
def build(value)
unless value.is_a?(::Numeric)
raise TypeError, "can't build an #{self.name} from a #{value.class.name}"
end
parts = {}
remainder_sign = value <=> 0
remainder = value.round(9).abs
variable = false
PARTS.each do |part|
unless part == :seconds
part_in_seconds = PARTS_IN_SECONDS[part]
parts[part] = remainder.div(part_in_seconds) * remainder_sign
remainder %= part_in_seconds
unless parts[part].zero?
variable ||= VARIABLE_PARTS.include?(part)
end
end
end unless value == 0
parts[:seconds] = remainder * remainder_sign
new(value, parts, variable)
end Создает новый Duration из значения в секундах, которое преобразуется в отдельные части:
ActiveSupport::Duration.build(31556952).parts # => {:years=>1}
ActiveSupport::Duration.build(2716146).parts # => {:months=>1, :days=>1}
# File activesupport/lib/active_support/duration.rb, line 143 def parse(iso8601duration) parts = ISO8601Parser.new(iso8601duration).parse! new(calculate_total_seconds(parts), parts) end
Создает новый Duration из строки, отформатированной в соответствии с ISO 8601 Duration.
См. ISO 8601 для получения дополнительной информации. Этот метод позволяет присутствовать отрицательным частям в шаблоне. Если предоставлена некорректная строка, он вызовет ActiveSupport::Duration::ISO8601Parser::ParsingError.
Методы публичного экземпляра
# File activesupport/lib/active_support/duration.rb, line 306
def %(other)
if Duration === other || Scalar === other
Duration.build(value % other.value)
elsif Numeric === other
Duration.build(value % other)
else
raise_type_error(other)
end
end Возвращает остаток от деления этого Duration на другой Duration или Numeric. Значения Numeric обрабатываются как секунды.
# File activesupport/lib/active_support/duration.rb, line 281
def *(other)
if Scalar === other || Duration === other
Duration.new(value * other.value, @parts.transform_values { |number| number * other.value }, @variable || other.variable?)
elsif Numeric === other
Duration.new(value * other, @parts.transform_values { |number| number * other }, @variable)
else
raise_type_error(other)
end
end Умножает этот Duration на Numeric и возвращает новый Duration.
# File activesupport/lib/active_support/duration.rb, line 262
def +(other)
if Duration === other
parts = @parts.merge(other._parts) do |_key, value, other_value|
value + other_value
end
Duration.new(value + other.value, parts, @variable || other.variable?)
else
seconds = @parts.fetch(:seconds, 0) + other
Duration.new(value + other, @parts.merge(seconds: seconds), @variable)
end
end Добавляет другой Duration или Numeric к этому Duration. Значения Numeric обрабатываются как секунды.
# File activesupport/lib/active_support/duration.rb, line 292
def /(other)
if Scalar === other
Duration.new(value / other.value, @parts.transform_values { |number| number / other.value }, @variable)
elsif Duration === other
value / other.value
elsif Numeric === other
Duration.new(value / other, @parts.transform_values { |number| number / other }, @variable)
else
raise_type_error(other)
end
end # File activesupport/lib/active_support/duration.rb, line 335
def ==(other)
if Duration === other
other.value == value
else
other == value
end
end Возвращает true если other также является экземпляром Duration с теми же value, или если other == value.
# File activesupport/lib/active_support/duration.rb, line 420 def eql?(other) Duration === other && other.value.eql?(value) end
Возвращает true если other также является экземпляром Duration, который имеет те же части, что и этот.
# File activesupport/lib/active_support/duration.rb, line 424 def hash @value.hash end
# File activesupport/lib/active_support/duration.rb, line 393 def in_days in_seconds / SECONDS_PER_DAY.to_f end
Возвращает количество дней, охватываемых продолжительностью, как число с плавающей точкой
12.hours.in_days # => 0.5
# File activesupport/lib/active_support/duration.rb, line 386 def in_hours in_seconds / SECONDS_PER_HOUR.to_f end
Возвращает количество часов, охватываемых продолжительностью, как число с плавающей точкой
1.day.in_hours # => 24.0
# File activesupport/lib/active_support/duration.rb, line 379 def in_minutes in_seconds / SECONDS_PER_MINUTE.to_f end
Возвращает количество минут, охватываемых продолжительностью, как число с плавающей точкой
1.day.in_minutes # => 1440.0
# File activesupport/lib/active_support/duration.rb, line 407 def in_months in_seconds / SECONDS_PER_MONTH.to_f end
Возвращает количество месяцев, охватываемых продолжительностью, как число с плавающей точкой
9.weeks.in_months # => 2.07
# File activesupport/lib/active_support/duration.rb, line 400 def in_weeks in_seconds / SECONDS_PER_WEEK.to_f end
Возвращает количество недель, охватываемых продолжительностью, как число с плавающей точкой
2.months.in_weeks # => 8.696
# File activesupport/lib/active_support/duration.rb, line 414 def in_years in_seconds / SECONDS_PER_YEAR.to_f end
Возвращает количество лет, охватываемых продолжительностью, как число с плавающей точкой
30.days.in_years # => 0.082
# File activesupport/lib/active_support/duration.rb, line 467 def iso8601(precision: nil) ISO8601Serializer.new(self, precision: precision).serialize end
Построение строки ISO 8601 для этой продолжительности. Параметр precision может использоваться для ограничения точности секунд продолжительности.
# File activesupport/lib/active_support/duration.rb, line 235 def parts @parts.dup end
Возвращает копию хэша частей, определяющих продолжительность
# File activesupport/lib/active_support/duration.rb, line 371 def to_i @value.to_i end
Возвращает количество секунд, которое представляет эта Duration.
1.minute.to_i # => 60 1.hour.to_i # => 3600 1.day.to_i # => 86400
Обратите внимание, что эта конвертация делает некоторые предположения о продолжительности некоторых периодов, например, месяцы всегда составляют 1/12 часть года, а годы — 365,2425 дней:
# equivalent to (1.year / 12).to_i 1.month.to_i # => 2629746 # equivalent to 365.2425.days.to_i 1.year.to_i # => 31556952
В таких случаях для точных вычислений дат и времени следует использовать встроенные в Ruby Date и Time.
# File activesupport/lib/active_support/duration.rb, line 347 def to_s @value.to_s end
Возвращает количество секунд, охватываемых длительностью, в виде строки. Для получения дополнительной информации см. метод to_i.
1.day.to_s # => "86400"
© 2004–2021 David Heinemeier Hansson
Licensed under the MIT License.