Class: Conversions::Unit
- Inherits:
-
Object
- Object
- Conversions::Unit
- Defined in:
- lib/conversions/unit.rb
Overview
Proxy class to contain the unit as well as reference the base value
Class Method Summary collapse
-
.conversion ⇒ Object
:nodoc:.
-
.exchange_rate(from_unit, to_unit) ⇒ Object
:nodoc:.
- .register(from, to, value) ⇒ Object
Instance Method Summary collapse
-
#initialize(value, from) ⇒ Unit
constructor
Create a new Unit instance.
-
#to(to, scale = nil) ⇒ Object
Convert to a certain other unit.
Constructor Details
#initialize(value, from) ⇒ Unit
Create a new Unit instance.
-
value: The value to convert from (ie. 4.92)
-
from: The unit to convert from (ie. :miles)
8 9 10 11 |
# File 'lib/conversions/unit.rb', line 8 def initialize(value, from) @value = value @from = from end |
Class Method Details
.conversion ⇒ Object
:nodoc:
31 32 33 34 |
# File 'lib/conversions/unit.rb', line 31 def self.conversion #:nodoc: map_conversion if !defined? @@conversion @@conversion end |
.exchange_rate(from_unit, to_unit) ⇒ Object
:nodoc:
22 23 24 25 26 27 28 29 |
# File 'lib/conversions/unit.rb', line 22 def self.exchange_rate(from_unit, to_unit) #:nodoc: return 1 if from_unit == to_unit from = conversion[from_unit] raise ArgumentError, "Can't convert from `#{from}', unknown unit" if from.nil? to = from[to_unit] raise ArgumentError, "Can't convert from `#{from_unit}' to `#{to_unit}', unknown unit" if to.nil? to end |
.register(from, to, value) ⇒ Object
36 37 38 39 40 |
# File 'lib/conversions/unit.rb', line 36 def self.register(from, to, value) CONVERSION.merge!(from.to_sym => { to.to_sym => value.to_f }) map_conversion Numeric.send :include, Conversions::Ext end |
Instance Method Details
#to(to, scale = nil) ⇒ Object
Convert to a certain other unit.
-
to: The unit to convert to (ie. :kilometers)
-
scale: The number of digits behind the decimal point to you want to keep (Optional)
17 18 19 20 |
# File 'lib/conversions/unit.rb', line 17 def to(to, scale=nil) value = @value * self.class.exchange_rate(@from, to) scale.nil? ? value : (value * (10 ** scale)).round / (10 ** scale).to_f end |