Module: Duration::Common

Includes:
Comparable
Included in:
Days, Hours, Microseconds, Milliseconds, Minutes, Months, Nanoseconds, Seconds, Weeks
Defined in:
lib/Duration/Common.rb

Instance Method Summary collapse

Instance Method Details

#*(other) ⇒ Object

A duration times a number is a duration. A duration times a duration would be time squared, which has no unit here and few enough anywhere, so it is refused rather than quietly given some plausible answer.



19
20
21
22
23
24
# File 'lib/Duration/Common.rb', line 19

def *(other)
  if other.is_a?(Duration::Common)
    raise TypeError, "can't multiply #{self.class} by #{other.class}: there is no unit of time squared"
  end
  scale(:*, other)
end

#+(other) ⇒ Object



8
9
10
# File 'lib/Duration/Common.rb', line 8

def +(other)
  combine(:+, other)
end

#-(other) ⇒ Object



12
13
14
# File 'lib/Duration/Common.rb', line 12

def -(other)
  combine(:-, other)
end

#/(other) ⇒ Object

Divided by a number a duration stays a duration. Divided by a duration it becomes the dimensionless ratio of the two, the units having cancelled, which is how a rate or a speedup is arrived at.



29
30
31
32
# File 'lib/Duration/Common.rb', line 29

def /(other)
  return ratio(other) if other.is_a?(Duration::Common)
  scale(:quo, other)
end

#<=>(other) ⇒ Object



34
35
36
37
# File 'lib/Duration/Common.rb', line 34

def <=>(other)
  return nil unless other.is_a?(Duration::Common)
  quantity <=> other.send(:"to_#{unit}").quantity
end

#inspectObject

The class and the quantity as it is actually held, after measurand: to_s is what a reader wants and inspect is what the object is. It is the one place the difference between an Integer 45 and a Rational 45/1 shows, which in a library this careful about exactness is worth being able to see.



53
54
55
# File 'lib/Duration/Common.rb', line 53

def inspect
  "#{self.class}(#{quantity.inspect})"
end

#to_sObject

The unit is the class, so naming it says which duration this is without repeating the class: 45 days rather than #<Duration::Days:0x000... The quantity is rendered as it is held, an exact Rational staying exact, this library manufacturing no precision it was not given and discarding none it was.



44
45
46
# File 'lib/Duration/Common.rb', line 44

def to_s
  "#{rendered_quantity} #{quantity == 1 ? unit.to_s.chomp('s') : unit}"
end