Module: Minitwin::ClassMethods::Rbs

Included in:
Minitwin::ClassMethods
Defined in:
lib/minitwin/class_methods/rbs.rb

Instance Method Summary collapse

Instance Method Details

#to_rbsObject

: () -> String



9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
# File 'lib/minitwin/class_methods/rbs.rb', line 9

def to_rbs
  # :nocov:
  return "" unless name

  lines = []
  superclass_name = superclass ? " < ::#{superclass.name}" : ""
  # :nocov:
  lines << "class ::#{name}#{superclass_name}"

  # Collect initializer parameters
  init_params = []

  props = properties
  props.each do |prop, meta|
    as_meta = meta[:as]
    # Dynamic aliases (Proc) cannot be represented statically in RBS;
    # fall back to the base property name.
    reader_name = as_meta && !as_meta.is_a?(Proc) && as_meta != prop ? as_meta : prop
    type = rbs_type_for(meta)
    lines << "  attr_reader #{reader_name}: #{type}"
    if method_defined?(:"#{prop}=", false)
      # :nocov:
      lines << "  attr_writer #{prop}: #{type}"
      # :nocov:
    end

    # Add to initializer parameters (all optional)
    init_params << "?#{prop}: #{type}"
  end

  collections.each do |name_sym, meta|
    elem_type = rbs_elem_type_for(meta)
    lines << "  attr_accessor #{name_sym}: ::Array[#{elem_type}]"

    # Add to initializer parameters (all optional, collections accept arrays or individual items)
    init_params << "?#{name_sym}: ::Array[#{elem_type}]"
  end

  # Add initializer signature
  lines << ""
  lines << if init_params.any?
             "  def initialize: (#{init_params.join(", ")}, **untyped) -> void"
           else
             "  def initialize: (**untyped) -> void"
           end

  lines << "end"
  lines.join("\n")
end