Class: CommerceUnits::Value

Inherits:
Object
  • Object
show all
Defined in:
lib/commerce_units/value.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(number = nil, unit = nil) ⇒ Value

Returns a new instance of Value.



10
11
12
13
# File 'lib/commerce_units/value.rb', line 10

def initialize(number=nil, unit=nil)
  @number = number
  @unit = unit
end

Instance Attribute Details

#numberObject

Returns the value of attribute number.



9
10
11
# File 'lib/commerce_units/value.rb', line 9

def number
  @number
end

#unitObject

Returns the value of attribute unit.



9
10
11
# File 'lib/commerce_units/value.rb', line 9

def unit
  @unit
end

Class Method Details

.from_params(number: number, units: units) ⇒ Object



3
4
5
# File 'lib/commerce_units/value.rb', line 3

def from_params(number: number, units: units)
  new number, CommerceUnits::UnitParser.parse(units)
end

Instance Method Details

#*(value) ⇒ Object



25
26
27
# File 'lib/commerce_units/value.rb', line 25

def *(value)
  self.class.new number * value.number, CommerceUnits::Unit.multiply(unit, value.unit)
end

#+(value) ⇒ Object



15
16
17
18
# File 'lib/commerce_units/value.rb', line 15

def +(value)
  v = _convert_units_to_match value
  self.class.new v.number + number, unit
end

#-(value) ⇒ Object



20
21
22
23
# File 'lib/commerce_units/value.rb', line 20

def -(value)
  v = _convert_units_to_match value
  self.class.new number - v.number, unit
end

#/(value) ⇒ Object



29
30
31
# File 'lib/commerce_units/value.rb', line 29

def /(value)
  self.class.new number / value.number, CommerceUnits::Unit.divide(unit, value.unit)
end

#==(value) ⇒ Object



44
45
46
47
# File 'lib/commerce_units/value.rb', line 44

def ==(value)
  v = _convert_units_to_match value
  number == v.number && unit == v.unit
end

#constant?Boolean

Returns:

  • (Boolean)


53
# File 'lib/commerce_units/value.rb', line 53

def constant?; unitless; end

#flipObject



33
34
35
36
37
38
# File 'lib/commerce_units/value.rb', line 33

def flip
  self.class.new.tap do |v|
    v.number = 1.0 / number
    v.unit = unit.flip
  end
end

#simplifyObject



40
41
42
# File 'lib/commerce_units/value.rb', line 40

def simplify
  CommerceUnits::TermsReducer.new(self).reduce_to_simplest_terms
end

#to_sObject



49
50
51
# File 'lib/commerce_units/value.rb', line 49

def to_s
  "#{number} #{unit.pretty_inspect}"
end