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 ~~~

Instance Attribute Summary

Attributes inherited from Base

#processable_constants

Instance Method Summary collapse

Methods inherited from Base

#handles?, #initialize

Constructor Details

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

Instance Method Details

#decorate(root, constant) ⇒ Object



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

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

  root.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)
      create_method(model, name.pluralize, class_method: true, return_type: type)
    end
  end
end

#gather_constantsObject



84
85
86
# File 'lib/tapioca/compilers/dsl/active_record_enum.rb', line 84

def gather_constants
  ::ActiveRecord::Base.descendants.reject(&:abstract_class?)
end