Sha256: 68dcb4313e7f42b85c7499ac7ce78baa723624ea4f0c3c5944800b2038e50667

Contents?: true

Size: 1.16 KB

Versions: 35

Compression:

Stored size: 1.16 KB

Contents

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

35 entries across 35 versions & 1 rubygems

Version Path
renalware-core-2.0.16 app/values/renalware/duration.rb
renalware-core-2.0.15 app/values/renalware/duration.rb
renalware-core-2.0.14 app/values/renalware/duration.rb
renalware-core-2.0.13 app/values/renalware/duration.rb
renalware-core-2.0.12 app/values/renalware/duration.rb
renalware-core-2.0.11 app/values/renalware/duration.rb
renalware-core-2.0.9 app/values/renalware/duration.rb
renalware-core-2.0.8 app/values/renalware/duration.rb
renalware-core-2.0.7 app/values/renalware/duration.rb
renalware-core-2.0.5 app/values/renalware/duration.rb
renalware-core-2.0.4 app/values/renalware/duration.rb
renalware-core-2.0.3 app/values/renalware/duration.rb
renalware-core-2.0.2 app/values/renalware/duration.rb
renalware-core-2.0.1 app/values/renalware/duration.rb
renalware-core-2.0.0 app/values/renalware/duration.rb
renalware-core-2.0.0.pre.rc13 app/values/renalware/duration.rb
renalware-core-2.0.0.pre.rc11 app/values/renalware/duration.rb
renalware-core-2.0.0.pre.rc10 app/values/renalware/duration.rb
renalware-core-2.0.0.pre.rc9 app/values/renalware/duration.rb
renalware-core-2.0.0.pre.rc8 app/values/renalware/duration.rb