Module: Baml

Defined in:
lib/struct.rb,
lib/baml.rb,
lib/stream.rb,
lib/checked.rb

Overview

require “pp”

Defined Under Namespace

Modules: Checks, Sorbet Classes: BamlStream, DynamicStruct

Constant Summary collapse

ClientRegistry =
Baml::Ffi::ClientRegistry
Image =
Baml::Ffi::Image
Audio =
Baml::Ffi::Audio
Checked =

Reexport Checked types.

Baml::Checks::Checked
Check =
Baml::Checks::Check

Class Method Summary collapse

Class Method Details

.convert_to(type) ⇒ Object

Dynamically + idempotently define Baml::TypeConverter NB: this does not respect raise_coercion_error = false



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
# File 'lib/baml.rb', line 23

def self.convert_to(type)
  if !Baml.const_defined?(:TypeConverter)
    Baml.const_set(:TypeConverter, Class.new(TypeCoerce::Converter) do
      def initialize(type)
        super(type)
      end
      
      def _convert(value, type, raise_coercion_error, coerce_empty_to_nil)
        # make string handling more strict
        if type == String
          if value.is_a?(String)
            return value
          end

          raise TypeCoerce::CoercionError.new(value, type)
        end

        # add unions
        if type.is_a?(T::Types::Union)
          type.types.each do |t|
            # require raise_coercion_error on the recursive union call,
            # so that we can suppress the error if it fails
            converted = _convert(value, t, true, coerce_empty_to_nil)
            return converted
          rescue
            # do nothing - try every instance of the union
          end

          raise TypeCoerce::CoercionError.new(value, type)
        end

        super(value, type, raise_coercion_error, coerce_empty_to_nil)
      end
    end)
  end

  Baml.const_get(:TypeConverter).new(type)
end