Module: Units

Included in:
Numeric
Defined in:
lib/units/base.rb

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args) ⇒ Object

The heart of unit conversion, it will handle methods like: to_seconds and cast the number accordingly.


9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/units/base.rb', line 9

def method_missing(symbol, *args)
  symbol = symbol.to_s.sub(/^to_/,'').intern if symbol.to_s =~ /^to_.+/
  
  to_kind, to_unit = lookup_unit(symbol)
  
  # If there is a kind and this is conversion and the aliases include the provided symbol, convert
  if to_kind && to_unit && self.class.all_unit_aliases(to_kind).include?(symbol)
    from_unit = (@unit || to_unit)
    from_kind = lookup_unit(from_unit).first

    if from_kind != to_kind
      raise UnitsError, "invalid conversion, cannot convert #{from_unit} (a #{from_kind}) to #{to_unit} (a #{to_kind})"

    else
      # The reason these numbers have to be floats instead of integers is that all similar integers are the same ones
      # in memory, so that @kind and @unit couldn't be different for different numbers
      case self.class.unit_conversions[to_kind]
        when Hash
          result = Float( self * self.class.unit_conversions[from_kind][from_unit] / self.class.unit_conversions[to_kind][to_unit] )
        when Symbol
          result = Float( self * send(self.class.unit_conversions[to_kind], from_unit, to_unit) )
      end        
    end
    
    result.instance_eval do
      @unit = to_unit
      @kind = to_kind
    end

    return result
  else
    super
  end
end

Instance Attribute Details

#kindObject (readonly)

Returns the value of attribute kind


5
6
7
# File 'lib/units/base.rb', line 5

def kind
  @kind
end

#unitObject (readonly) Also known as: units

Returns the value of attribute unit


5
6
7
# File 'lib/units/base.rb', line 5

def unit
  @unit
end