Class: PackList::Weight

Inherits:
Object
  • Object
show all
Defined in:
lib/packlist/model.rb

Constant Summary collapse

WEIGHT_CONVERSIONS =
{lb: 453.592, oz: 453.592 / 16, kg: 1000, g: 1}
ZERO =
Weight.new(0, :g)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(quantity, units) ⇒ Weight

Returns a new instance of Weight.

Raises:

  • (ArgumentError)


16
17
18
19
# File 'lib/packlist/model.rb', line 16

def initialize(quantity, units)
  raise ArgumentError, "Invalid units: #{units}" unless WEIGHT_CONVERSIONS.key?(units)
  @quantity, @units = quantity, units
end

Instance Attribute Details

#quantityObject (readonly)

Returns the value of attribute quantity.



14
15
16
# File 'lib/packlist/model.rb', line 14

def quantity
  @quantity
end

#unitsObject (readonly)

Returns the value of attribute units.



14
15
16
# File 'lib/packlist/model.rb', line 14

def units
  @units
end

Instance Method Details

#*(x) ⇒ Object



41
42
43
# File 'lib/packlist/model.rb', line 41

def *(x)
  Weight.new x * @quantity, @units
end

#+(w) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/packlist/model.rb', line 27

def +(w)
  # avoid changing units when either weight is zero
  case
  when w.quantity == 0
    self
  when self.quantity == 0
    w
  when w.units == @units
    Weight.new w.quantity + @quantity, @units
  else
    self + w.to_units(@units)
  end
end

#in_units(new_units) ⇒ Object

private



48
49
50
# File 'lib/packlist/model.rb', line 48

def in_units(new_units)
  quantity * WEIGHT_CONVERSIONS[units] / WEIGHT_CONVERSIONS[new_units]
end

#to_sObject



56
57
58
# File 'lib/packlist/model.rb', line 56

def to_s
  "#{'%.1f' % quantity} #{units}"
end

#to_units(new_units) ⇒ Object



52
53
54
# File 'lib/packlist/model.rb', line 52

def to_units(new_units)
  Weight.new in_units(new_units), new_units
end