Class: Tapioca::Dsl::Compilers::Structure

Inherits:
Compiler
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/tapioca/dsl/compilers/structure.rb

Overview

Generates RBI files for Structure-based Data classes.

For example, given:

Person = Structure.new do
  attribute :name, String
  attribute? :age, Integer
end

This compiler will generate:

class Person < Data
  sig { params(name: String, age: T.nilable(Integer)).returns(Person) }
  sig { params(name: String, age: T.nilable(Integer)).void }
  def initialize(name:, age: nil); end

  sig { returns(String) }
  def name; end

  sig { returns(T.nilable(Integer)) }
  def age; end

  sig { params(data: T::Hash[T.any(String, Symbol), T.untyped]).returns(Person) }
  def self.parse(data = {}); end
end

: [ConstantType = singleton(::Data)]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.gather_constantsObject



42
43
44
45
46
# File 'lib/tapioca/dsl/compilers/structure.rb', line 42

def gather_constants
  all_classes.select do |klass|
    klass < ::Data && klass.respond_to?(:__structure_meta__)
  end
end

Instance Method Details

#decorateObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/tapioca/dsl/compilers/structure.rb', line 50

def decorate
  meta = constant.__structure_meta__
  return unless meta

  attributes = meta[:mappings]&.keys || constant.members
  types = meta.fetch(:types, {})
  required = meta.fetch(:required, attributes)
  non_nullable = meta.fetch(:non_nullable, [])

  root.create_path(constant) do |klass|
    generate_new_and_brackets(klass, attributes, types, required, non_nullable)
    generate_parse(klass)
    generate_load_dump(klass)
    generate_members(klass, attributes)
    generate_attr_readers(klass, attributes, types, non_nullable, required)
    generate_to_h(klass, attributes, types, non_nullable, required)
    generate_boolean_predicates(klass, types)
  end
end