Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions lib/openai/base_model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ def type_info(spec)
type_info(spec.slice(:const, :enum, :union).first&.last)
in Proc
spec
in OpenAI::Converter | Class
in OpenAI::Converter | Class | Symbol
-> { spec }
in true | false
-> { OpenAI::BooleanModel }
in NilClass | true | false | Symbol | Integer | Float
in NilClass | Integer | Float
-> { spec.class }
end
end
Expand All @@ -82,6 +82,13 @@ def coerce(target, value)
case target
in OpenAI::Converter
target.coerce(value)
in Symbol
case value
in Symbol | String if (val = value.to_sym) == target
val
else
value
end
in Class
case target
in -> { _1 <= NilClass }
Expand Down Expand Up @@ -140,6 +147,13 @@ def try_strict_coerce(target, value)
case target
in OpenAI::Converter
target.try_strict_coerce(value)
in Symbol
case value
in Symbol | String if (val = value.to_sym) == target
[true, val, 1]
else
[false, false, 0]
end
in Class
case [target, value]
in [-> { _1 <= NilClass }, _]
Expand Down Expand Up @@ -367,7 +381,14 @@ class << self
#
# @return [Symbol, Object]
#
def coerce(value) = (value.is_a?(String) ? value.to_sym : value)
def coerce(value)
case value
in Symbol | String if values.include?(val = value.to_sym)
val
else
value
end
end

# @!parse
# # @private
Expand All @@ -388,7 +409,7 @@ def try_strict_coerce(value)
return [true, value, 1] if values.include?(value)

case value
in String if values.include?(val = value.to_sym)
in Symbol | String if values.include?(val = value.to_sym)
[true, val, 1]
else
case [value, values.first]
Expand Down
16 changes: 15 additions & 1 deletion test/openai/base_model_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def test_basic_coerce
end

assert_pattern do
OpenAI::Converter.coerce(A2, %w[a b c]) => [:a, :b, :c]
OpenAI::Converter.coerce(A2, %w[a b c]) => [:a, :b, "c"]
end
end

Expand Down Expand Up @@ -338,4 +338,18 @@ def test_basic_eql
refute_equal(U1, U2)
assert_equal(U1, U3)
end

class U4 < OpenAI::Union
variant :a, const: :a
variant :b, const: :b
end

def test_basic_const_union
assert_pattern do
U4.coerce(nil) => nil
U4.coerce("") => ""
U4.coerce(:a) => :a
U4.coerce("a") => :a
end
end
end