Class: SorbetRails::ModelPlugins::ActiveRecordEnum

Inherits:
Base
  • Object
show all
Defined in:
lib/sorbet-rails/model_plugins/active_record_enum.rb

Constant Summary

Constants inherited from Base

Base::Parameter

Instance Attribute Summary

Attributes inherited from Base

#available_classes, #model_class

Instance Method Summary collapse

Methods inherited from Base

#initialize

Methods included from SorbetRails::ModelUtils

#exists_class_method?, #exists_instance_method?, #model_assoc_proxy_class_name, #model_class, #model_class_name, #model_module_name, #model_relation_class_name, #model_relation_shared_module_name

Constructor Details

This class inherits a constructor from SorbetRails::ModelPlugins::Base

Instance Method Details

#generate(root) ⇒ Object



6
7
8
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
# File 'lib/sorbet-rails/model_plugins/active_record_enum.rb', line 6

def generate(root)
  return unless model_class.defined_enums.size > 0

  enum_module_name = model_module_name("EnumInstanceMethods")
  enum_module_rbi = root.create_module(enum_module_name)
  enum_module_rbi.create_extend("T::Sig")

  model_class_rbi = root.create_class(self.model_class_name)
  model_class_rbi.create_include(enum_module_name)

  model_relation_shared_rbi = root.create_module(self.model_relation_shared_module_name)

  # TODO: add any method for signature verification?
  model_class.defined_enums.sort.each do |enum_name, enum_hash|
    model_class_rbi.create_method(
      enum_name.pluralize,
      return_type: "T::Hash[T.any(String, Symbol), Integer]",
      class_method: true,
    )
    enum_hash.keys.each do |enum_val|
      enum_module_rbi.create_method(
        "#{enum_val}?",
        return_type: "T::Boolean",
      )
      enum_module_rbi.create_method(
        "#{enum_val}!",
        return_type: nil, # void
      )
      # force generating these methods because sorbet's hidden-definitions generate & override them
      model_class_rbi.create_method(
        "#{enum_val}",
        return_type: self.model_relation_class_name,
        class_method: true,
      )
    end
  end
end