Class: Azure::ServiceBus::Interval

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/azure/service_bus/interval.rb

Overview

Public: Helper class to decorate a numeric duration so it can be output as an ISO8601-compliant Duration. (This class only implements the subset of the ISO8601 standard that the Azure REST API uses.)

Examples

# Initialize an Interval from a Number, or use .try_convert to be
# intelligent:

Interval.new(10)              #=> PT10S
Interval.try_convert(10)      #=> PT10S
Interval.try_convert("PT10S") #=> PT10S
Interval.try_convert(nil)     #=> nil

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.parse(string) ⇒ Object

Public: Parse a String into an Interval.

string - A String in the Interval format.

Returns an Interval.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/azure/service_bus/interval.rb', line 56

def self.parse(string)
  re = /P([\d\.\,]+Y)?([\d\.\,]+M)?([\d\.\,]+D)?(?:T([\d\.\,]+H)?([\d\.\,]+M)?([\d\.\,]+S)?)?/

  match = re.match(string)

  return nil if match.nil?

  #years   = match[1].to_f
  #months  = match[2].to_f         
  days    = match[3].to_f
  hours   = match[4].to_f
  minutes = match[5].to_f
  seconds = match[6].to_f 

  new(seconds + minutes * 60 + hours * 3600 + days * 86400)
end

.try_convert(object) ⇒ Object

Public: Attempt to convert an object into an Interval.

object - An object that might be converted into an Interval.

Returns an Interval or nil.



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/azure/service_bus/interval.rb', line 39

def self.try_convert(object)
  if object.respond_to?(:to_interval)
    object.to_interval
  elsif object.respond_to?(:to_int)
    new(object)
  elsif object.respond_to?(:to_str)
    parse(object)
  else
    nil
  end
end

Instance Method Details

#to_intervalObject

Public: Convert this object into an interval.

Returns self.



99
100
101
# File 'lib/azure/service_bus/interval.rb', line 99

def to_interval
  self
end

#to_sObject Also known as: inspect

Public: Return this amount of seconds formatted as an interval.

Returns a String.



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/azure/service_bus/interval.rb', line 76

def to_s
  days    = to_i / 86400
  hours   = (to_i % 86400) / 3600
  minutes = (to_i % 3600) / 60
  seconds = (self % 60)

  days = "%<d>s" % {
    :d => days.zero? ? nil : "#{days}D"
  }

  time = "%<h>s%<m>s%<s>s" % {
    :h => hours.zero?               ? nil : "#{hours}H",
    :m => minutes.zero?             ? nil : "#{minutes}M",
    :s => nonzero? && seconds.zero? ? nil : "#{seconds}S"
  }

  "P#{days}" + (time.empty? ? "" : "T#{time}")
end