Sha256: bf6fa77ce50b538c067eb44b3bbbed2ffaa69747de6a9c5af2627242e4fd464d

Contents?: true

Size: 1.17 KB

Versions: 7

Compression:

Stored size: 1.17 KB

Contents

# frozen_string_literal: true

require "date"
require "bigdecimal"
require "bigdecimal/util"
require "time"

module Dry
  module Types
    module Coercions
      # JSON-specific coercions
      #
      # @api public
      module JSON
        extend Coercions

        # @param [Object] input
        #
        # @return [nil] if the input is nil
        #
        # @raise CoercionError
        #
        # @api public
        def self.to_nil(input, &_block)
          if input.nil?
            nil
          elsif block_given?
            yield
          else
            raise CoercionError, "#{input.inspect} is not nil"
          end
        end

        # @param [#to_d, Object] input
        #
        # @return [BigDecimal,nil]
        #
        # @raise CoercionError
        #
        # @api public
        def self.to_decimal(input, &_block)
          if input.is_a?(::Float)
            input.to_d
          else
            BigDecimal(input)
          end
        rescue ArgumentError, TypeError
          if block_given?
            yield
          else
            raise CoercionError, "#{input} cannot be coerced to decimal"
          end
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
dry-types-1.7.2 lib/dry/types/coercions/json.rb
dry-types-1.7.1 lib/dry/types/coercions/json.rb
dry-types-1.7.0 lib/dry/types/coercions/json.rb
dry-types-1.6.1 lib/dry/types/coercions/json.rb
dry-types-1.6.0 lib/dry/types/coercions/json.rb
dry-types-1.5.1 lib/dry/types/coercions/json.rb
dry-types-1.5.0 lib/dry/types/coercions/json.rb