Sha256: dfc5e8f77d8b6c2b2877f9dcf0f63ce210c3577366e83bfd5ad97c5137a35c98

Contents?: true

Size: 1.19 KB

Versions: 142

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

module Renalware
  class Duration
    attr_reader :seconds

    class Minute
      def self.to_seconds(value)
        value.to_i * 60
      end
    end

    class Hour
      def self.to_seconds(value)
        value.to_i * Minute.to_seconds(60)
      end
    end

    def initialize(seconds)
      @seconds = seconds
    end

    def self.from_string(value)
      Duration.new(to_seconds(value))
    end

    def self.from_minutes(minutes)
      minutes = 0 if minutes.nil? || minutes.blank?
      seconds = minutes.to_i * 60
      Duration.new(seconds)
    end

    # Returns the duration in hours and minutes format: "hh:mm"
    def to_s
      return "" if @seconds.nil?

      hours, seconds = @seconds.divmod(Hour.to_seconds(1))
      minutes = seconds / Minute.to_seconds(1)
      sprintf("%d:%02d", hours, minutes)
    end

    def self.to_seconds(string)
      return nil if string.blank?

      case string
      when /(?<hours>\d+):(?<minutes>\d{2})/ # "hh:mm"
        match = $LAST_MATCH_INFO
        Hour.to_seconds(match[:hours]) + Minute.to_seconds(match[:minutes])
      else
        Minute.to_seconds(string)
      end
    end

    private_class_method :to_seconds
  end
end

Version data entries

142 entries across 142 versions & 1 rubygems

Version Path
renalware-core-2.0.147 app/values/renalware/duration.rb
renalware-core-2.0.146 app/values/renalware/duration.rb
renalware-core-2.0.145 app/values/renalware/duration.rb
renalware-core-2.0.144 app/values/renalware/duration.rb
renalware-core-2.0.143 app/values/renalware/duration.rb
renalware-core-2.0.142 app/values/renalware/duration.rb
renalware-core-2.0.141 app/values/renalware/duration.rb
renalware-core-2.0.140 app/values/renalware/duration.rb
renalware-core-2.0.139 app/values/renalware/duration.rb
renalware-core-2.0.138 app/values/renalware/duration.rb
renalware-core-2.0.137 app/values/renalware/duration.rb
renalware-core-2.0.136 app/values/renalware/duration.rb
renalware-core-2.0.135 app/values/renalware/duration.rb
renalware-core-2.0.134 app/values/renalware/duration.rb
renalware-core-2.0.133 app/values/renalware/duration.rb
renalware-core-2.0.132 app/values/renalware/duration.rb
renalware-core-2.0.131 app/values/renalware/duration.rb
renalware-core-2.0.130 app/values/renalware/duration.rb
renalware-core-2.0.129 app/values/renalware/duration.rb
renalware-core-2.0.128 app/values/renalware/duration.rb