Class: Numeric

Inherits:
Object
  • Object
show all
Defined in:
lib/unitwise/ext/numeric.rb

Overview

Unitwise extends Numeric to add these dyanmic method conveniences: ‘1.meter`, `26.2.to_mile`, and `4.convert_to(“Joule”)`. These overrides are optional due to their controversial nature. `require ’unitwise/ext’‘ to enable them.

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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

Converts numeric to a measurement by the method name

Examples:

26.2.mile # => #<Unitwise::Measurement 26.2 mile>
100.to_foot # => #<Unitwise::Measurement 100 foot>


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/unitwise/ext/numeric.rb', line 20

def method_missing(meth, *args, &block)
  if args.empty? && !block_given?
    unit = (match = /\Ato_(\w+)\Z/.match(meth.to_s)) ? match[1] : meth
    converted = begin
      convert_to(unit)
    rescue Unitwise::ExpressionError
      nil
    end
  end
  if converted
    Numeric.define_unit_conversion_methods_for(unit)
    converted
  else
    super(meth, *args, &block)
  end
end

Class Method Details

.define_unit_conversion_methods_for(name) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/unitwise/ext/numeric.rb', line 37

def self.define_unit_conversion_methods_for(name)
  [name.to_sym, "to_#{ name }".to_sym].each do |meth|
    next if method_defined?(meth)
    define_method meth do
      convert_to(name)
    end
  end
end

Instance Method Details

#convert_to(unit) ⇒ Unitwise::Measurement

Converts numeric to a measurement

Examples:

26.2.convert_to('mile') # => #<Unitwise::Measurement 1 mile>

Parameters:

  • unit (Unitwise::Unit, String)

    The unit to use in the measurement

Returns:



11
12
13
# File 'lib/unitwise/ext/numeric.rb', line 11

def convert_to(unit)
  Unitwise::Measurement.new(self, unit)
end