Class: Unit::SimpleUnit

Inherits:
BaseUnit show all
Includes:
Comparable
Defined in:
lib/unitmanager/simple_unit.rb

Overview

Implementation of what is called ‘simple unit of measure’. This is a linear unit which is optionally based on some other simple unit with linear coefficient. Example: :cm is based on :mm with coefficient equal 10. In other words X cm = 10 * Y mm.

Constant Summary collapse

@@EMPTY_UNIT =
SimpleUnit.new()

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Comparable

#compatible?, #contains?

Methods inherited from BaseUnit

#[], once

Constructor Details

#initialize(args = {}) ⇒ SimpleUnit

Returns a new instance of SimpleUnit.



98
99
100
101
102
# File 'lib/unitmanager/simple_unit.rb', line 98

def initialize (args = {})
  @unit = args[:unit]
  @based_on = args[:based_on] || nil
  @coefficient = args[:coefficient] || 1
end

Instance Attribute Details

#based_onObject (readonly)

include Unit::Singleton



94
95
96
# File 'lib/unitmanager/simple_unit.rb', line 94

def based_on
  @based_on
end

#coefficientObject (readonly)

include Unit::Singleton



94
95
96
# File 'lib/unitmanager/simple_unit.rb', line 94

def coefficient
  @coefficient
end

#unitObject (readonly)

include Unit::Singleton



94
95
96
# File 'lib/unitmanager/simple_unit.rb', line 94

def unit
  @unit
end

Instance Method Details

#==(other) ⇒ Object

Two Simple units are equal if they have same symbol, based on the same unit with the same coefficient



132
133
134
135
136
137
# File 'lib/unitmanager/simple_unit.rb', line 132

def ==(other)
  return false if other == nil
  return false unless other.kind_of?(self.class)
  
  unit == other.unit && based_on == other.based_on && coefficient == other.coefficient     
end

#dividendObject



122
123
124
# File 'lib/unitmanager/simple_unit.rb', line 122

def dividend
  @unit
end

#divisorObject



126
127
128
# File 'lib/unitmanager/simple_unit.rb', line 126

def divisor
  @@EMPTY_UNIT
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


139
140
141
# File 'lib/unitmanager/simple_unit.rb', line 139

def eql?(other)
  self == other
end

#from_base(value) ⇒ Object



110
111
112
113
114
# File 'lib/unitmanager/simple_unit.rb', line 110

def from_base(value)
  value = @based_on.from_base(value) if derived?
  
  value /= @coefficient
end

#h_baseObject

Returns unit representing hierarchy base for the given unit. The Hierarchy is the “based on” chain.



118
119
120
# File 'lib/unitmanager/simple_unit.rb', line 118

def h_base
  derived? ? @based_on.h_base : self
end

#to_base(value) ⇒ Object



104
105
106
107
108
# File 'lib/unitmanager/simple_unit.rb', line 104

def to_base(value)
  value = @based_on.to_base(value) if derived?
  
  value *= @coefficient
end