Class: Tapioca::Compilers::Dsl::ActiveRecordEnum

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

Overview

‘Tapioca::Compilers::Dsl::ActiveRecordEnum` decorates RBI files for subclasses of `ActiveRecord::Base` which declare [`enum` fields](api.rubyonrails.org/classes/ActiveRecord/Enum.html).

For example, with the following ‘ActiveRecord::Base` subclass:

~~~rb class Post < ApplicationRecord

enum title_type: %i(book all web), _suffix: :title

end ~~~

this generator will produce the RBI file ‘post.rbi` with the following content:

~~~rbi # post.rbi # typed: true class Post

include EnumMethodsModule

module EnumMethodsModule
  sig { void }
  def all_title!; end

  sig { returns(T::Boolean) }
  def all_title?; end

  sig { returns(T::Hash[T.any(String, Symbol), Integer]) }
  def self.title_types; end

  sig { void }
  def book_title!; end

  sig { returns(T::Boolean) }
  def book_title?; end

  sig { void }
  def web_title!; end

  sig { returns(T::Boolean) }
  def web_title?; end
end

end ~~~

Constant Summary

Constants included from Reflection

Reflection::ANCESTORS_METHOD, Reflection::CLASS_METHOD, Reflection::CONSTANTS_METHOD, Reflection::EQUAL_METHOD, Reflection::METHOD_METHOD, Reflection::NAME_METHOD, Reflection::OBJECT_ID_METHOD, Reflection::PRIVATE_INSTANCE_METHODS_METHOD, Reflection::PROTECTED_INSTANCE_METHODS_METHOD, Reflection::PUBLIC_INSTANCE_METHODS_METHOD, Reflection::SINGLETON_CLASS_METHOD, Reflection::SUPERCLASS_METHOD

Instance Attribute Summary

Attributes inherited from Base

#errors, #processable_constants

Instance Method Summary collapse

Methods inherited from Base

#add_error, #handles?, #initialize

Methods included from Reflection

#ancestors_of, #are_equal?, #class_of, #constants_of, #descendants_of, #inherited_ancestors_of, #method_of, #name_of, #name_of_type, #object_id_of, #private_instance_methods_of, #protected_instance_methods_of, #public_instance_methods_of, #qualified_name_of, #signature_of, #singleton_class_of, #superclass_of

Constructor Details

This class inherits a constructor from Tapioca::Compilers::Dsl::Base

Instance Method Details

#decorate(root, constant) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/tapioca/compilers/dsl/active_record_enum.rb', line 62

def decorate(root, constant)
  return if constant.defined_enums.empty?

  root.create_path(constant) do |model|
    module_name = "EnumMethodsModule"

    model.create_module(module_name) do |mod|
      generate_instance_methods(constant, mod)
    end

    model.create_include(module_name)

    constant.defined_enums.each do |name, enum_map|
      type = type_for_enum(enum_map)
      model.create_method(name.pluralize, class_method: true, return_type: type)
    end
  end
end

#gather_constantsObject



82
83
84
# File 'lib/tapioca/compilers/dsl/active_record_enum.rb', line 82

def gather_constants
  descendants_of(::ActiveRecord::Base)
end