Module: Quickbooks::Support::TimeInterval

Defined in:
lib/quickbooks/ruby_ext.rb

Class Method Summary collapse

Class Method Details

.new(whatever) ⇒ Object

The TIMEINTERVALTYPE type takes the form PTnHnMnS: The characters P and T are always present. • The character H follows the number of hours. • The character M follows the number of minutes. • The character S follows the number of seconds. • n is an integer that represents the number of hours, minutes, or seconds. Examples:

PT2H30M0S means: 2 hours, 30 minutes
PT2H0M0S means: 2 hours
PT0H0M5S means: 5 seconds


234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/quickbooks/ruby_ext.rb', line 234

def self.new(whatever)
  case
  when whatever.is_a?(String) && whatever =~ /PT\d\d?H\d\d?M\d\d?S/
    whatever
  when whatever.is_a?(String) && whatever =~ /(\d\d?):(\d\d?)(?:\.(\d\d?))?/
    s, hours, minutes, seconds = *whatever.match(/(\d\d?):(\d\d?)(?:\.(\d\d?))?/)
    "PT#{hours.to_i}H#{minutes.to_i}M#{seconds.to_i}S"
  when whatever.is_a?(Duration)
    hours = whatever.hours.to_i
    minutes = (whatever - hours.hours).minutes.to_i
    seconds = (whatever - hours.hours - minutes.minutes).seconds.to_i
    "PT#{hours}H#{minutes}M#{seconds}S"
  else
    raise ArgumentError, "duration given must be either a String formatted correctly (/PT\d\d?H\d\d?M\d\d?S/, where ) or a Duration object (try whatever english makes sense: 1.hour + 20.minutes, for example.)"
  end
end