Module: T::Private::Casts

Defined in:
lib/types/private/casts.rb

Class Method Summary collapse

Class Method Details

.cast(value, type, cast_method) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/types/private/casts.rb', line 6

def self.cast(value, type, cast_method)
  begin
    coerced_type = T::Utils::Private.coerce_and_check_module_types(type, value, true)
    return value unless coerced_type

    error = coerced_type.error_message_for_obj(value)
    return value unless error

    caller_loc = T.must(caller_locations(2..2)).first

    suffix = "Caller: #{T.must(caller_loc).path}:#{T.must(caller_loc).lineno}"

    raise TypeError.new("#{cast_method}: #{error}\n#{suffix}")
  rescue TypeError => e # raise into rescue to ensure e.backtrace is populated
    T::Configuration.inline_type_error_handler(e, {kind: cast_method, value: value, type: type})
    value
  end
end

.cast_recursive(value, type, cast_method) ⇒ Object

there’s a lot of shared logic with the above one, but factoring it out like this makes it easier to hopefully one day delete this one



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/types/private/casts.rb', line 28

def self.cast_recursive(value, type, cast_method)
  begin
    error = T::Utils.coerce(type).error_message_for_obj_recursive(value)
    return value unless error

    caller_loc = T.must(caller_locations(2..2)).first

    suffix = "Caller: #{T.must(caller_loc).path}:#{T.must(caller_loc).lineno}"

    raise TypeError.new("#{cast_method}: #{error}\n#{suffix}")
  rescue TypeError => e # raise into rescue to ensure e.backtrace is populated
    T::Configuration.inline_type_error_handler(e, {kind: cast_method, value: value, type: type})
    value
  end
end