dry-rb/dry-types

View on GitHub
lib/dry/types/coercions.rb

Summary

Maintainability
A
50 mins
Test Coverage
A
100%
# frozen_string_literal: true

module Dry
  module Types
    # Common coercion functions used by the built-in `Params` and `JSON` types
    #
    # @api public
    module Coercions
      include Dry::Core::Constants

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

      # @param [#to_str, Object] input
      #
      # @return [Date, Object]
      #
      # @see Date.parse
      #
      # @api public
      def to_date(input, &block)
        if input.respond_to?(:to_str)
          begin
            ::Date.parse(input)
          rescue ArgumentError, RangeError => e
            CoercionError.handle(e, &block)
          end
        elsif block_given?
          yield
        else
          raise CoercionError, "#{input.inspect} is not a string"
        end
      end

      # @param [#to_str, Object] input
      #
      # @return [DateTime, Object]
      #
      # @see DateTime.parse
      #
      # @api public
      def to_date_time(input, &block)
        if input.respond_to?(:to_str)
          begin
            ::DateTime.parse(input)
          rescue ArgumentError => e
            CoercionError.handle(e, &block)
          end
        elsif block_given?
          yield
        else
          raise CoercionError, "#{input.inspect} is not a string"
        end
      end

      # @param [#to_str, Object] input
      #
      # @return [Time, Object]
      #
      # @see Time.parse
      #
      # @api public
      def to_time(input, &block)
        if input.respond_to?(:to_str)
          begin
            ::Time.parse(input)
          rescue ArgumentError => e
            CoercionError.handle(e, &block)
          end
        elsif block_given?
          yield
        else
          raise CoercionError, "#{input.inspect} is not a string"
        end
      end

      # @param [#to_sym, Object] input
      #
      # @return [Symbol, Object]
      #
      # @raise CoercionError
      #
      # @api public
      def to_symbol(input, &block)
        input.to_sym
      rescue NoMethodError => e
        CoercionError.handle(e, &block)
      end

      private

      # Checks whether String is empty
      #
      # @param [String, Object] value
      #
      # @return [Boolean]
      #
      # @api private
      def empty_str?(value)
        EMPTY_STRING.eql?(value)
      end
    end
  end
end