Module: Structure::RBS

Defined in:
lib/structure/rbs.rb

Overview

Generates RBS type signatures for Structure classes

Class Method Summary collapse

Class Method Details

.emit(klass) ⇒ Object



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
# File 'lib/structure/rbs.rb', line 16

def emit(klass)
  return unless klass < Data

  class_name = klass.name
  return unless class_name

  # @type var meta: Hash[Symbol, untyped]
  meta = klass.respond_to?(:__structure_meta__) ? klass.__structure_meta__ : {}

  attributes = meta[:mappings] ? meta[:mappings].keys : klass.members
  # @type var types: Hash[Symbol, untyped]
  default_types = _ = {} #: Hash[Symbol, untyped]
  types = meta.fetch(:types, default_types)
  # @type var required: Array[Symbol]
  required = meta.fetch(:required, attributes)
  non_nullable = meta.fetch(:non_nullable, [])
  custom_methods = meta.fetch(:custom_methods, EMPTY_CUSTOM_METHODS)

  emit_rbs_content(
    class_name:,
    attributes:,
    types:,
    required:,
    non_nullable:,
    has_structure_modules: meta.any?,
    custom_methods:,
  )
end

.write(klass, dir: "sig") ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/structure/rbs.rb', line 45

def write(klass, dir: "sig")
  rbs_content = emit(klass)
  return unless rbs_content

  # User::Address -> user/address.rbs
  path_segments = klass.name.split("::").map(&:downcase)
  filename = "#{path_segments.pop}.rbs"

  # full path
  dir_path = Pathname.new(dir)
  dir_path = dir_path.join(*path_segments) unless path_segments.empty?
  FileUtils.mkdir_p(dir_path)

  file_path = dir_path.join(filename).to_s
  File.write(file_path, rbs_content)

  file_path
end

.write_all(classes, dir: "sig") ⇒ Array<String>

Write RBS files for multiple classes or all Structure classes in a module

Examples:

With array of classes

Structure::RBS.write_all([Person, Address, Order])

With module namespace

Structure::RBS.write_all(Peddler::Models)


75
76
77
78
79
# File 'lib/structure/rbs.rb', line 75

def write_all(classes, dir: "sig")
  classes = structure_classes_in(classes) if classes.is_a?(Module)

  classes.filter_map { |klass| write(klass, dir: dir) }
end