Class: Tapioca::Dsl::Compilers::RailsSorbetEnumCompiler

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

Overview

This Tapioca compiler generates RBI for Rails models that include RailsSorbetEnum::Concern.

Constant Summary collapse

ConstantType =
type_member { { fixed: T.class_of(RailsSorbetEnum::Concern) } }
RBI_MODULE_NAME =
"RailsSorbetEnumMethods"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.gather_constantsObject



23
24
25
26
# File 'lib/tapioca/dsl/compilers/rails_sorbet_enum_compiler.rb', line 23

def gather_constants
  all_classes
    .select { |c| c < RailsSorbetEnum::Concern }
end

Instance Method Details

#decorateObject



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
58
59
60
# File 'lib/tapioca/dsl/compilers/rails_sorbet_enum_compiler.rb', line 30

def decorate
  root.create_path(constant) do |klass|
    klass.create_module(RBI_MODULE_NAME) do |methods_mod|
      T.unsafe(constant).sorbet_enum_attributes.each do |enum_name, enum_type|
        type_with_nilability =
          if T.unsafe(constant).column_for_attribute(enum_name).null
            "T.nilable(#{enum_type.name})"
          else
            enum_type.name
          end

        methods_mod.create_method(
          "#{enum_name}=",
          parameters: [
            create_param("value", type: type_with_nilability)
          ],
          return_type: "void"
        )

        enum_type.each_value do |enum_value|
          value_name = enum_value.instance_variable_get(:@const_name).to_s.downcase
          methods_mod.create_method(
            "#{enum_name}_#{value_name}?",
            return_type: "T::Boolean"
          )
        end
      end
    end
    klass.create_include(RBI_MODULE_NAME)
  end
end