Module: TypeSpecFromSerializers::Sorbet

Defined in:
lib/typespec_from_serializers/sorbet.rb

Overview

Public: Sorbet integration for type inference.

This module provides optional integration with Sorbet’s runtime type system and RBI files. It can extract type information from:

  1. Runtime signatures (T::Utils.signature_for_method)

  2. RBI files generated by Tapioca (in sorbet/rbi/ directory)

The module gracefully degrades when sorbet-runtime is not present, making Sorbet integration completely optional with zero configuration required.

Class Method Summary collapse

Class Method Details

.available?Boolean

Public: Check if Sorbet runtime is available.

Returns true if sorbet-runtime gem is loaded and the necessary APIs are available for type extraction.

Returns Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/typespec_from_serializers/sorbet.rb', line 22

def available?
  !!(defined?(T::Utils) && T::Utils.respond_to?(:signature_for_method))
end

.extract_type_for(klass, method_name) ⇒ Object

Public: Extract type information for a method from its Sorbet signature.

Tries multiple sources in order:

  1. Runtime reflection (T::Utils.signature_for_method)

  2. RBI files (if available)

klass - The Class containing the method method_name - The Symbol or String name of the method

Returns a Hash with keys:

:typespec_type - Symbol or String representing the TypeSpec type
:nilable       - Boolean indicating if type is optional
:array         - Boolean indicating if type is an array

Returns nil if no signature found

Examples

class MySerializer
  extend T::Sig

  sig { returns(String) }
  def name
    "example"
  end
end

extract_type_for(MySerializer, :name)
# => { typespec_type: :string, nilable: false, array: false }


77
78
79
80
81
82
# File 'lib/typespec_from_serializers/sorbet.rb', line 77

def extract_type_for(klass, method_name)
  # Try TypeDSL first (if available), then runtime reflection, then RBI files
  extract_from_type_dsl(klass, method_name) ||
    (available? ? extract_from_runtime(klass, method_name) : nil) ||
    (rbi_available? ? extract_from_rbi(klass, method_name) : nil)
end

.rbi_available?Boolean

Public: Check if RBI files are available for parsing.

Returns true if sorbet/rbi/ directory exists (typical Tapioca setup).

Returns Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/typespec_from_serializers/sorbet.rb', line 44

def rbi_available?
  !rbi_path.nil?
end

.rbi_pathObject

Public: Get the RBI directory path.

Returns Pathname or nil if directory doesn’t exist or can’t be accessed



29
30
31
32
33
34
35
36
37
# File 'lib/typespec_from_serializers/sorbet.rb', line 29

def rbi_path
  return @rbi_path if defined?(@rbi_path)

  @rbi_path = begin
    TypeSpecFromSerializers.rbi_dir.then { |path| path if path.exist? && path.directory? }
  rescue
    nil
  end
end