Class: Unitwise::Measurement

Inherits:
Scale
  • Object
show all
Defined in:
lib/unitwise/measurement.rb

Instance Attribute Summary

Attributes inherited from Scale

#value

Instance Method Summary collapse

Methods inherited from Scale

#atoms, #depth, #dup, #functional, #inspect, #root_terms, #scalar, #special?, #terminal?, #terms, #to_s, #unit

Methods included from Composable

#<=>, #composition, #composition_string, #dim, included, #similar_to?

Constructor Details

#initialize(value, unit) ⇒ Measurement



4
5
6
7
8
9
# File 'lib/unitwise/measurement.rb', line 4

def initialize(value, unit)
  super(value, unit)
  if terms.nil?
    raise ExpressionError, "Could not evaluate `#{unit}`."
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/unitwise/measurement.rb', line 44

def method_missing(meth, *args, &block)
  if Unitwise::Expression.decompose(meth)
    self.convert(meth)
  else
    super(meth, *args, &block)
  end
end

Instance Method Details

#*(other) ⇒ Object



20
21
22
# File 'lib/unitwise/measurement.rb', line 20

def *(other)
  operate(:*, other) || raise(TypeError, "Can't multiply #{inspect} by #{other}.")
end

#**(number) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/unitwise/measurement.rb', line 36

def **(number)
  if number.is_a?(Numeric)
    new( value ** number, unit ** number )
  else
    raise TypeError, "Can't raise #{inspect} to #{number} power."
  end
end

#+(other) ⇒ Object



28
29
30
# File 'lib/unitwise/measurement.rb', line 28

def +(other)
  combine(:+, other) || raise(TypeError, "Can't add #{other} to #{inspect}.")
end

#-(other) ⇒ Object



32
33
34
# File 'lib/unitwise/measurement.rb', line 32

def -(other)
  combine(:-, other) || raise(TypeError, "Can't subtract #{other} from #{inspect}.")
end

#/(other) ⇒ Object



24
25
26
# File 'lib/unitwise/measurement.rb', line 24

def /(other)
  operate(:/, other) || raise(TypeError, "Can't divide #{inspect} by #{other}")
end

#convert(other_unit) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/unitwise/measurement.rb', line 11

def convert(other_unit)
  other_unit = Unit.new(other_unit)
  if similar_to?(other_unit)
    new(converted_value(other_unit), other_unit)
  else
    raise ConversionError, "Can't convert #{inspect} to #{other_unit}."
  end
end