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.
- #to_f ⇒ Object
- #to_i ⇒ Object
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_name, to_unit_name) ⇒ Object
:nodoc:
38 39 40 41 42 43 44 45 |
# File 'lib/conversions/unit.rb', line 38 def self.exchange_rate(from_unit_name, to_unit_name) #:nodoc: return 1 if from_unit_name == to_unit_name from = Conversions.conversions[from_unit_name] raise ArgumentError, "[conversions] No unit named `#{from_unit_name}'" if from.blank? to = from[to_unit_name] raise ArgumentError, "[conversions] No exchange rate defined from `#{from_unit_name}' to `#{to_unit_name}'" if to.blank? to end |
Instance Method Details
#to(to, options = {}) ⇒ Object
Convert to a certain other unit.
-
to: The unit to convert to (ie. :kilometers)
-
options:
-
:scale: The number of digits behind the decimal point to you want to keep
-
26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/conversions/unit.rb', line 26 def to(to, ={}) case when Integer scale = when Hash scale = [:scale] end value = @value * self.class.exchange_rate(@from, to) scale.nil? ? value : (value * (10 ** scale)).round / (10 ** scale).to_f end |
#to_f ⇒ Object
17 18 19 |
# File 'lib/conversions/unit.rb', line 17 def to_f @value.to_f end |
#to_i ⇒ Object
13 14 15 |
# File 'lib/conversions/unit.rb', line 13 def to_i @value.to_i end |