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 (see https://api.rubyonrails.org/classes/ActiveRecord/Enum.html).

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

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:

# post.rbi
# typed: true
class Post
  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

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



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

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

  module_name = "#{constant}::EnumMethodsModule"
  root.create_module(module_name) do |mod|
    generate_instance_methods(constant, mod)
  end

  root.path(constant) do |k|
    k.create_include(module_name)

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

#gather_constantsObject



80
81
82
# File 'lib/tapioca/compilers/dsl/active_record_enum.rb', line 80

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