Class: LetsCert::ValidTime

Inherits:
Object
  • Object
show all
Defined in:
lib/letscert/valid_time.rb

Overview

Class used to process validation time from String.

Author:

  • Sylvain Daubert

Constant Summary collapse

SECONDS_IN_ONE_MINUTE =

Number of seconds in one minute

60
SECONDS_IN_ONE_HOUR =

Number of seconds in one hour

60 * 60
SECONDS_IN_ONE_DAY =

Number of seconds in one day

24 * 60 * 60

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ ValidTime

Returns a new instance of ValidTime.

Parameters:

  • str (String)

    time string. May be:

    • an integer -> time in seconds

    • an integer plus a letter:

      • 30m: 30 minutes,

      • 30h: 30 hours,

      • 30d: 30 days.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/letscert/valid_time.rb', line 56

def initialize(str)
  m = str.match(/^(\d+)([mhd])?$/)
  if m
    @seconds = case m[2]
               when nil
                 m[1].to_i
               when 'm'
                 m[1].to_i * SECONDS_IN_ONE_MINUTE
               when 'h'
                 m[1].to_i * SECONDS_IN_ONE_HOUR
               when 'd'
                 m[1].to_i * SECONDS_IN_ONE_DAY
               end
  else
    raise OptionParser::InvalidArgument,
          "invalid argument: valid-min #{str}"
  end
  @string = str
end

Class Method Details

.time_in_words(seconds) ⇒ String

Get time in words (e.g. xx days or xx hours)

Parameters:

  • seconds (Integer)

Returns:

  • (String)


38
39
40
41
42
43
44
45
46
47
48
# File 'lib/letscert/valid_time.rb', line 38

def self.time_in_words(seconds)
  if seconds < SECONDS_IN_ONE_MINUTE
    '%u seconds' % seconds
  elsif seconds < SECONDS_IN_ONE_HOUR
    'about %u minutes' % (seconds / SECONDS_IN_ONE_MINUTE)
  elsif seconds < SECONDS_IN_ONE_DAY
    'about %u hours' % (seconds / SECONDS_IN_ONE_HOUR)
  else
    'about %u days' % (seconds / SECONDS_IN_ONE_DAY)
  end
end

Instance Method Details

#to_sString

Get time as string

Returns:

  • (String)


84
85
86
# File 'lib/letscert/valid_time.rb', line 84

def to_s
  @string
end

#to_secondsInteger

Get time in seconds

Returns:

  • (Integer)


78
79
80
# File 'lib/letscert/valid_time.rb', line 78

def to_seconds
  @seconds
end