Class: PackList::Weight
- Inherits:
-
Object
- Object
- PackList::Weight
- 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
-
#quantity ⇒ Object
readonly
Returns the value of attribute quantity.
-
#units ⇒ Object
readonly
Returns the value of attribute units.
Instance Method Summary collapse
- #*(x) ⇒ Object
- #+(w) ⇒ Object
-
#in_units(new_units) ⇒ Object
private.
-
#initialize(quantity, units) ⇒ Weight
constructor
A new instance of Weight.
- #to_s ⇒ Object
- #to_units(new_units) ⇒ Object
Constructor Details
#initialize(quantity, units) ⇒ Weight
Returns a new instance of Weight.
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
#quantity ⇒ Object (readonly)
Returns the value of attribute quantity.
14 15 16 |
# File 'lib/packlist/model.rb', line 14 def quantity @quantity end |
#units ⇒ Object (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_s ⇒ Object
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 |