Sha256: 440176b0f26c0973a227816784c2b09d4d73568371f4f930d15fa33880d8db84

Contents?: true

Size: 1.8 KB

Versions: 11

Compression:

Stored size: 1.8 KB

Contents

# frozen_string_literal: true
require 'bigdecimal'

class Money
  module Helpers
    module_function

    NUMERIC_REGEX = /\A\s*[\+\-]?(\d+|\d*\.\d+)\s*\z/
    DECIMAL_ZERO = BigDecimal(0).freeze
    MAX_DECIMAL = 21

    def value_to_decimal(num)
      value =
        case num
        when Money
          num.value
        when BigDecimal
          num
        when nil, 0, ''
          DECIMAL_ZERO
        when Integer
          BigDecimal(num)
        when Float
          BigDecimal(num, Float::DIG)
        when Rational
          BigDecimal(num, MAX_DECIMAL)
        when String
          string_to_decimal(num)
        else
          raise ArgumentError, "could not parse as decimal #{num.inspect}"
        end
      return DECIMAL_ZERO if value.sign == BigDecimal::SIGN_NEGATIVE_ZERO
      value
    end

    def value_to_currency(currency)
      case currency
      when Money::Currency, Money::NullCurrency
        currency
      when nil, ''
        default = Money.current_currency || Money.default_currency
        raise(ArgumentError, 'missing currency') if default.nil? || default == ''
        value_to_currency(default)
      when 'xxx', 'XXX'
        Money::NULL_CURRENCY
      when String
        begin
          Currency.find!(currency)
        rescue Money::Currency::UnknownCurrency => error
          Money.deprecate(error.message)
          Money::NULL_CURRENCY
        end
      else
        raise ArgumentError, "could not parse as currency #{currency.inspect}"
      end
    end

    def string_to_decimal(num)
      if num =~ NUMERIC_REGEX
        return BigDecimal(num)
      end

      Money.deprecate("using Money.new('#{num}') is deprecated and will raise an ArgumentError in the next major release")
      begin
        BigDecimal(num)
      rescue ArgumentError
        DECIMAL_ZERO
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
shopify-money-0.14.1 lib/money/helpers.rb
shopify-money-0.14.0 lib/money/helpers.rb
shopify-money-0.13.1 lib/money/helpers.rb
shopify-money-0.13.0 lib/money/helpers.rb
shopify-money-0.12.0 lib/money/helpers.rb
shopify-money-0.11.9 lib/money/helpers.rb
shopify-money-0.11.8 lib/money/helpers.rb
shopify-money-0.11.7 lib/money/helpers.rb
shopify-money-0.11.6 lib/money/helpers.rb
shopify-money-0.11.5 lib/money/helpers.rb
shopify-money-0.11.4 lib/money/helpers.rb