Class: Conversions::Unit

Inherits:
Object
  • Object
show all
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

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:

Raises:

  • (ArgumentError)


30
31
32
33
34
35
36
37
# File 'lib/conversions/unit.rb', line 30

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)

  • options:

    • :scale: The number of digits behind the decimal point to you want to keep



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/conversions/unit.rb', line 18

def to(to, options={})
  case options
  when Integer
    scale = options
  when Hash
    scale = options[:scale]
  end
  
  value = @value * self.class.exchange_rate(@from, to)
  scale.nil? ? value : (value * (10 ** scale)).round / (10 ** scale).to_f
end