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
Instance Method Summary collapse
-
#initialize(value, from) ⇒ Unit
constructor
Create a new Unit instance.
-
#to(to, options = {}) ⇒ 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
.exchange_rate(from_unit, to_unit) ⇒ Object
:nodoc:
23 24 25 26 27 28 29 30 |
# File 'lib/conversions/unit.rb', line 23 def self.exchange_rate(from_unit, to_unit) #:nodoc: return 1 if from_unit == to_unit from = Conversions.conversions[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 |
Instance Method Details
#to(to, options = {}) ⇒ 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 21 |
# File 'lib/conversions/unit.rb', line 17 def to(to, = {}) scale = .delete(:scale) value = @value * self.class.exchange_rate(@from, to) scale.nil? ? value : (value * (10 ** scale)).round / (10 ** scale).to_f end |