Sha256: 0d7a5687c7026340aa8333276fb7e28167ad9d91b093e77afed63e1bdf5cc4a7

Contents?: true

Size: 1.28 KB

Versions: 5

Compression:

Stored size: 1.28 KB

Contents

module Conversions
  # Proxy class to contain the unit as well as reference the base value
  class Unit
    # Create a new Unit instance.
    #
    # * _value_: The value to convert from (ie. 4.92)
    # * _from_: The unit to convert from (ie. :miles)
    def initialize(value, from)
      @value = value
      @from = from
    end
    
    def to_i
      @value.to_i
    end
    
    def to_f
      @value.to_f
    end

    # 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
    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

    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
  end
end

Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
seamusabshere-conversions-1.4.1 lib/conversions/unit.rb
seamusabshere-conversions-1.4.2 lib/conversions/unit.rb
conversions-1.4.5 lib/conversions/unit.rb
conversions-1.4.4 lib/conversions/unit.rb
conversions-1.4.3 lib/conversions/unit.rb