Class: Numeric
- Inherits:
-
Object
- Object
- Numeric
- 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
and may be enabled with require 'unitwise/ext'. These methods are known to
reduce performance, as well as violate Ruby best practices. They are
deprecated and will be removed in a future version.
Class Method Summary collapse
Instance Method Summary collapse
-
#convert_to(unit) ⇒ Unitwise::Measurement
Converts numeric to a measurement.
-
#method_missing(meth, *args, &block) ⇒ Object
Converts numeric to a measurement by the method name.
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
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/unitwise/ext/numeric.rb', line 22 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
39 40 41 42 43 44 45 46 |
# File 'lib/unitwise/ext/numeric.rb', line 39 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
13 14 15 |
# File 'lib/unitwise/ext/numeric.rb', line 13 def convert_to(unit) Unitwise::Measurement.new(self, unit) end |