in lib/openai/internal/type/converter.rb [134:231]
def coerce(
target,
value,
state: {strictness: true, exactness: {yes: 0, no: 0, maybe: 0}, branched: 0}
)
strictness, exactness = state.fetch_values(:strictness, :exactness)
case target
in OpenAI::Internal::Type::Converter
return target.coerce(value, state: state)
in Class
if value.is_a?(target)
exactness[:yes] += 1
return value
end
case target
in -> { _1 <= NilClass }
exactness[value.nil? ? :yes : :maybe] += 1
return nil
in -> { _1 <= Integer }
if value.is_a?(Integer)
exactness[:yes] += 1
return value
elsif strictness == :strong && Integer(value, exception: false) != value
message = "no implicit conversion of #{value.class} into #{target.inspect}"
raise value.is_a?(Numeric) ? ArgumentError.new(message) : TypeError.new(message)
else
Kernel.then do
return Integer(value).tap { exactness[:maybe] += 1 }
rescue ArgumentError, TypeError
end
end
in -> { _1 <= Float }
if value.is_a?(Numeric)
exactness[:yes] += 1
return Float(value)
elsif strictness == :strong
message = "no implicit conversion of #{value.class} into #{target.inspect}"
raise TypeError.new(message)
else
Kernel.then do
return Float(value).tap { exactness[:maybe] += 1 }
rescue ArgumentError, TypeError
end
end
in -> { _1 <= String }
case value
in String | Symbol | Numeric
exactness[value.is_a?(Numeric) ? :maybe : :yes] += 1
return value.to_s
in StringIO
exactness[:yes] += 1
return value.string
else
if strictness == :strong
message = "no implicit conversion of #{value.class} into #{target.inspect}"
raise TypeError.new(message)
end
end
in -> { _1 <= Date || _1 <= Time }
Kernel.then do
return target.parse(value).tap { exactness[:yes] += 1 }
rescue ArgumentError, TypeError => e
raise e if strictness == :strong
end
in -> { _1 <= StringIO } if value.is_a?(String)
exactness[:yes] += 1
return StringIO.new(value.b)
else
end
in Symbol
case value
in Symbol | String
if value.to_sym == target
exactness[:yes] += 1
return target
else
exactness[:maybe] += 1
return value
end
else
if strictness == :strong
message = "cannot convert non-matching #{value.class} into #{target.inspect}"
raise ArgumentError.new(message)
end
end
else
end
exactness[:no] += 1
value
end