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.1.1 app/values/renalware/duration.rb
renalware-core-2.1.0 app/values/renalware/duration.rb
renalware-core-2.0.167 app/values/renalware/duration.rb
renalware-core-2.0.166 app/values/renalware/duration.rb
renalware-core-2.0.165 app/values/renalware/duration.rb
renalware-core-2.0.164 app/values/renalware/duration.rb
renalware-core-2.0.163 app/values/renalware/duration.rb
renalware-core-2.0.162 app/values/renalware/duration.rb
renalware-core-2.0.161 app/values/renalware/duration.rb
renalware-core-2.0.160 app/values/renalware/duration.rb
renalware-core-2.0.159 app/values/renalware/duration.rb
renalware-core-2.0.158 app/values/renalware/duration.rb
renalware-core-2.0.157 app/values/renalware/duration.rb
renalware-core-2.0.156 app/values/renalware/duration.rb
renalware-core-2.0.155 app/values/renalware/duration.rb
renalware-core-2.0.153 app/values/renalware/duration.rb
renalware-core-2.0.152 app/values/renalware/duration.rb
renalware-core-2.0.151 app/values/renalware/duration.rb
renalware-core-2.0.149 app/values/renalware/duration.rb
renalware-core-2.0.148 app/values/renalware/duration.rb