class Tapioca::Dsl::Compilers::ActiveRecordEnum
~~~
end
end
def web_title?; end
sig { returns(T::Boolean) }
def web_title!; end
sig { void }
def book_title?; end
sig { returns(T::Boolean) }
def book_title!; end
sig { void }
def self.title_types; end
sig { returns(T::Hash[T.any(String, Symbol), Integer]) }
def all_title?; end
sig { returns(T::Boolean) }
def all_title!; end
sig { void }
module EnumMethodsModule
include EnumMethodsModule
class Post
# typed: true
# post.rbi
~~~rbi
this compiler will produce the RBI file ‘post.rbi` with the following content:
~~~
end
enum title_type: %i(book all web), _suffix: :title
class Post < ApplicationRecord
~~~rb
For example, with the following `ActiveRecord::Base` subclass:
`ActiveRecord::Base` which declare [`enum` fields](api.rubyonrails.org/classes/ActiveRecord/Enum.html).
`Tapioca::Dsl::Compilers::ActiveRecordEnum` decorates RBI files for subclasses of
def decorate
def decorate 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(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
def gather_constants
def gather_constants descendants_of(::ActiveRecord::Base) end
def generate_instance_methods(klass)
def generate_instance_methods(klass) methods = constant.send(:_enum_methods_module).instance_methods methods.each do |method| method = method.to_s return_type = method.end_with?("?") ? "T::Boolean" : "void" klass.create_method(method, return_type: return_type) end end
def type_for_enum(enum_map)
def type_for_enum(enum_map) value_type = enum_map.values.map { |v| v.class.name }.uniq value_type = if value_type.length == 1 value_type.first else "T.any(#{value_type.join(", ")})" end "T::Hash[T.any(String, Symbol), #{value_type}]" end