Class: Tapioca::Compilers::PolymorphicBelongsTo

Inherits:
Dsl::Compiler
  • Object
show all
Extended by:
T::Generic
Defined in:
lib/tapioca/dsl/compilers/polymorphic_belongs_to.rb

Constant Summary collapse

ConstantType =
type_member { {fixed: T.class_of(ActiveRecord::Base)} }

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.gather_constantsObject



15
16
17
18
19
20
# File 'lib/tapioca/dsl/compilers/polymorphic_belongs_to.rb', line 15

def self.gather_constants
  all_classes.select do |klass|
    klass < ActiveRecord::Base &&
      klass.respond_to?(:polymorphic_belongs_to_types)
  end
end

Instance Method Details

#decorateObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/tapioca/dsl/compilers/polymorphic_belongs_to.rb', line 22

def decorate
  defined = T.unsafe(constant).polymorphic_belongs_to_types
  return unless defined&.any?

  root.create_path(constant) do |model|
    model.create_module("GeneratedPolymorphicAssociationMethods") do |mod|
      defined.each do |name, types|
        union =
          if types.length == 1
            "::#{T.must(types.first).name}"
          else
            "T.any(#{types.map { |t| "::#{t.name}" }.join(", ")})"
          end

        return_type = optional?(name) ? "T.nilable(#{union})" : union

        mod.create_method(name, return_type: return_type)
      end
    end

    model.create_include("GeneratedPolymorphicAssociationMethods")
  end
end