class method self.build

Ruby on Rails 7.0.10

Since v5.2.8.1

Available in: v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

self.build(value)

Creates a new Duration from a seconds value that is converted to the individual parts:

ActiveSupport::Duration.build(31556952).parts # => {:years=>1}
ActiveSupport::Duration.build(2716146).parts  # => {:months=>1, :days=>1}

Parameters

value req
Source
# 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

Defined in activesupport/lib/active_support/duration.rb line 188 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveSupport::Duration

Type at least 2 characters to search.

↑↓ navigate · open · esc close