1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
|
# 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 input.is_a?(::Date)
input
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 input.is_a?(::DateTime)
input
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 input.is_a?(::Time)
input
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
|