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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
|
# frozen_string_literal: true
require 'bigdecimal'
require 'bigdecimal/util'
module Dry
module Types
module Coercions
# Params-specific coercions
#
# @api public
module Params
TRUE_VALUES = %w[1 on On ON t true True TRUE T y yes Yes YES Y].freeze
FALSE_VALUES = %w[0 off Off OFF f false False FALSE F n no No NO N].freeze
BOOLEAN_MAP = ::Hash[
TRUE_VALUES.product([true]) + FALSE_VALUES.product([false])
].merge(true => true, false => false).freeze
extend Coercions
# @param [String, Object] input
#
# @return [Boolean,Object]
#
# @see TRUE_VALUES
# @see FALSE_VALUES
#
# @raise CoercionError
#
# @api public
def self.to_true(input, &_block)
BOOLEAN_MAP.fetch(input.to_s) do
if block_given?
yield
else
raise CoercionError, "#{input} cannot be coerced to true"
end
end
end
# @param [String, Object] input
#
# @return [Boolean,Object]
#
# @see TRUE_VALUES
# @see FALSE_VALUES
#
# @raise CoercionError
#
# @api public
def self.to_false(input, &_block)
BOOLEAN_MAP.fetch(input.to_s) do
if block_given?
yield
else
raise CoercionError, "#{input} cannot be coerced to false"
end
end
end
# @param [#to_int, #to_i, Object] input
#
# @return [Integer, nil, Object]
#
# @raise CoercionError
#
# @api public
def self.to_int(input, &block)
if input.is_a? String
Integer(input, 10)
else
Integer(input)
end
rescue ArgumentError, TypeError => e
CoercionError.handle(e, &block)
end
# @param [#to_f, Object] input
#
# @return [Float, nil, Object]
#
# @raise CoercionError
#
# @api public
def self.to_float(input, &block)
Float(input)
rescue ArgumentError, TypeError => e
CoercionError.handle(e, &block)
end
# @param [#to_d, Object] input
#
# @return [BigDecimal, nil, Object]
#
# @raise CoercionError
#
# @api public
def self.to_decimal(input, &block)
to_float(input) do
if block_given?
return yield
else
raise CoercionError, "#{input.inspect} cannot be coerced to decimal"
end
end
input.to_d
end
# @param [Array, String, Object] input
#
# @return [Array, Object]
#
# @raise CoercionError
#
# @api public
def self.to_ary(input, &_block)
if empty_str?(input)
[]
elsif input.is_a?(::Array)
input
elsif block_given?
yield
else
raise CoercionError, "#{input.inspect} cannot be coerced to array"
end
end
# @param [Hash, String, Object] input
#
# @return [Hash, Object]
#
# @raise CoercionError
#
# @api public
def self.to_hash(input, &_block)
if empty_str?(input)
{}
elsif input.is_a?(::Hash)
input
elsif block_given?
yield
else
raise CoercionError, "#{input.inspect} cannot be coerced to hash"
end
end
end
end
end
end
|