Sha256: b19a8b93106ea8969b3d6f4018f64321edba7857c875320e33ccf6b499d874ca

Contents?: true

Size: 1.16 KB

Versions: 12

Compression:

Stored size: 1.16 KB

Contents

# frozen_string_literal: true
class Money
  module Parser
    class Simple
      SIGNED_DECIMAL_MATCHER = /\A-?\d*(?:\.\d*)?\z/.freeze

      class << self
        # Parses an input string using BigDecimal, it always expects a dot character as a decimal separator and
        # generally does not accept other characters other than minus-hyphen and digits. It is useful for APIs, interop
        # with other languages and other use cases where you expect well-formatted input and do not need to take user
        # locale into consideration.
        # @param input [String]
        # @param currency [String, Money::Currency]
        # @param strict [Boolean]
        # @return [Money, nil]
        def parse(input, currency, strict: false)
          currency = Money::Helpers.value_to_currency(currency)
          return unless currency

          coerced = input.to_s
          if SIGNED_DECIMAL_MATCHER.match?(coerced) && (amount = BigDecimal(coerced, exception: false))
            Money.new(amount, currency)
          elsif strict
            raise ArgumentError, "unable to parse input=\"#{input}\" currency=\"#{currency}\""
          end
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
shopify-money-3.0.0 lib/money/parser/simple.rb
shopify-money-2.2.2 lib/money/parser/simple.rb
shopify-money-2.2.1 lib/money/parser/simple.rb
shopify-money-2.2.0 lib/money/parser/simple.rb
shopify-money-2.0.0 lib/money/parser/simple.rb
shopify-money-1.3.0 lib/money/parser/simple.rb
shopify-money-1.2.1 lib/money/parser/simple.rb
shopify-money-1.2.0 lib/money/parser/simple.rb
shopify-money-1.1.2 lib/money/parser/simple.rb
shopify-money-1.1.1 lib/money/parser/simple.rb
shopify-money-1.1.0 lib/money/parser/simple.rb
shopify-money-1.0.2.pre lib/money/parser/simple.rb