# frozen_string_literal: true require 'money' require 'monetize' require 'active_support/core_ext/string/output_safety' module Spree # Spree::Money is a relatively thin wrapper around Monetize which handles # formatting via Spree::Config. class Money include Comparable DifferentCurrencyError = Class.new(StandardError) RUBY_NUMERIC_STRING = /\A-?\d+(\.\d+)?\z/ class <(other) if !other.respond_to?(:money) raise TypeError, "Can't compare #{other.class} to Spree::Money" end if currency != other.currency # By default, ::Money will try to run a conversion on `other.money` and # try a comparison on that. We do not want any currency conversion to # take place so we'll catch this here and raise an error. raise( DifferentCurrencyError, "Can't compare #{currency} with #{other.currency}" ) end @money <=> other.money end # Delegates comparison to the internal ruby money instance. # # @see http://www.rubydoc.info/gems/money/Money/Arithmetic#%3D%3D-instance_method def ==(other) raise TypeError, "Can't compare #{other.class} to Spree::Money" if !other.respond_to?(:money) @money == other.money end def -(other) raise TypeError, "Can't subtract #{other.class} to Spree::Money" if !other.respond_to?(:money) self.class.new(@money - other.money) end def +(other) raise TypeError, "Can't add #{other.class} to Spree::Money" if !other.respond_to?(:money) self.class.new(@money + other.money) end end end