Sha256: afa7c4c950c3c44b2026bcbe040f9ceab37ca84751eec61e07831bd4667c83e6

Contents?: true

Size: 1.28 KB

Versions: 4

Compression:

Stored size: 1.28 KB

Contents

# -*- encoding : utf-8 -*-
module Exchange
  
  # Make Floating Points forget about their incapabilities when dealing with money
  #
  module ErrorSafe
    
    # Installs a method chain that overwrites the old error prone meth with the new one
    #
    def self.money_error_preventing_method_chain base, meth
      base.send :alias_method, :"#{meth}with_errors", meth
      base.send :alias_method, meth, :"#{meth}without_errors"
    end
    
    # @!macro prevent_errors_with_exchange_for
    #   Prevents float errors when dealing with instances of Exchange::Money
    #   By Typecasting the float into a Big Decimal
    #   @method $1(other)
    #
    def self.prevent_errors_with_exchange_for base, meth
      base.send(:define_method, :"#{meth}without_errors", lambda { |other|
        if other.is_a?(Exchange::Money)
          BigDecimal.new(self.to_s).send(meth, other.value).to_f
        else
          send(:"#{meth}with_errors", other)
        end
      })
      money_error_preventing_method_chain base, meth
    end
    
    def self.included base
      %W(* / + -).each do |meth|
        
        # @macro prevent_errors_with_exchange_for
        #
        prevent_errors_with_exchange_for base, meth.to_sym
        
      end
    end
    
  end
  
end

Float.send(:include, Exchange::ErrorSafe)

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
exchange-1.1.0 lib/exchange/core_extensions/float/error_safe.rb
exchange-1.0.4 lib/exchange/core_extensions/float/error_safe.rb
exchange-1.0.2 lib/exchange/core_extensions/float/error_safe.rb
exchange-1.0.0 lib/exchange/core_extensions/float/error_safe.rb