Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

sorbet-rails

> 后端框架
Open source

A set of tools to make the Sorbet typechecker work with Ruby on Rails seamlessly.

631 stars0 likes1 views
WebsiteGitHub

About

A set of tools to make the Sorbet typechecker work with Ruby on Rails seamlessly.

Notice

This repository is no longer maintained and will be sunset. The Sorbet community has endorsed the Tapioca gem for generating RBI's, including those for Rails. Please consider migrating over!

sorbet-rails

A set of tools to make the Sorbet typechecker work with Ruby on Rails seamlessly.

This gem adds a few Rake tasks to generate Ruby Interface (RBI) files for dynamic methods generated by Rails. It also includes signatures for related Rails classes. The RBI files are added to a sorbet/rails-rbi/ folder.

sorbet-rails supports Rails 5+ or later.

Notice: we no longer support Rails 4.2. Version 0.5.6 is the last version supporting Rails 4.2.

Initial Setup

  1. Follow the steps here to set up the latest version of Sorbet, up to being able to run srb tc.

  2. Add sorbet-rails to your Gemfile and install them with Bundler.

# -- Gemfile --
gem 'sorbet-rails'

Add sorbet-rails to the :default group because of "Features Provided at Runtime" below.

bash
❯ bundle install
  1. Generate RBI files for your routes, models, etc
bash
❯ bundle exec rake rails_rbi:routes
❯ bundle exec rake rails_rbi:models
❯ bundle exec rake rails_rbi:helpers
❯ bundle exec rake rails_rbi:mailers
❯ bundle exec rake rails_rbi:jobs
❯ bundle exec rake rails_rbi:custom

# or run them all at once
❯ bundle exec rake rails_rbi:all
  1. Update hidden-definition files and automatically upgrade each file's typecheck level:
bash
❯ bundle exec srb rbi hidden-definitions
❯ bundle exec srb rbi suggest-typed

Because we've generated RBI files for routes, models, and helpers, a lot more files should be typecheckable now. Many methods in hidden.rbi may be removed because they are now typed.

Static RBI Generation

Models

This Rake task generates RBI files for all models in the Rails application (all descendants of ActiveRecord::Base):

bash
❯ bundle exec rake rails_rbi:models

You can also regenerate RBI files for specific models. To accommodate for STI, this will generate rbi for all the subclasses of the models included.

bash
❯ bundle exec rake rails_rbi:models[ModelName,AnotherOne,...]

The generation task currently creates the following signatures:

  • Column getters & setters
  • Associations getters & setters
  • Enum values, checkers & scopes
  • Named scopes
  • Model Relation class
    • Scopes on Relation, but not class methods

It is possible to add custom RBI generation logic for your custom module or gems via the plugin system. Check out the plugins section below if you are interested.

We also add following methods to make type-checking easier:

  • find_n, first_n, last_n
  • pluck_to_tstruct
  • typed_enum
  • Model::RelationType

pluck_to_tstruct instead of pluck

The pluck method in Rails is a performant way to query value without instantiating ActiveRecord objects. However, it doesn't have any type information: it doesn't have type information (or name) of the attribute plucked. Sorbet-rails provides pluck_to_tstruct method as a replacement that returns an array of T::Struct instead. The attributes plucked is based on props defined in the T::Struct

ruby
# -- API
Arel.pluck_to_tstruct(TA[  ].new)

# -- example
class WizardStruct  ].new, associations:  >)

# -- example
class WizardWithWandStruct  MyActionParams
    # T.reveal_type(typed_params.show) => T.nilable(T::Boolean)
  end
end

If it fails to coerce the params into the right type, an ActionController::BadRequest exception will be raised with the coercion context for debugging.

Note: The API TypedParams[...].new.extract! may seem verbose, but necessary to support this feature. Ideally, the API can be simply TypedParams.extract!(...). However, sorbet doesn't support defining a method that accept a type and return an instance of the type. If this feature is supported by sorbet in the future, it will be easy to codemod to be TypedParams.extract(...)! part from your code. Note: require_typed and fetch_typed are deprecated in favor of TypedParams. They will be removed in v0.7.

Routes

This Rake task generates an RBI file defining _path and _url methods for all named routes in routes.rb:

bash
❯ bundle exec rake rails_rbi:routes

Helpers

This Rake task generates a helpers.rbi file that includes a basic module definition which includes the Kernel module and ActionView::Helpers, to allow for some basic Ruby methods to be used in helpers without Sorbet complaining.

bash
❯ bundle exec rake rails_rbi:helpers

If you have additional modules that are included in all your helpers and you want helpers.rbi to reflect this, you can configure it:

ruby
# -- config/initializers/sorbet_rails.rb
SorbetRails.configure do |config|
  config.extra_helper_includes = ['ApplicationHelper', 'Devise::Controllers::Helpers']
end

Mailers

This Rake task generates RBI files for all mailer classes in the Rails application (all descendants of ActionMailer::Base)

bash
❯ bundle exec rake rails_rbi:mailers

Since mailing action methods are based on instance methods defined in a mailer class, the signature of a mailing action method will be dependent on the signature the instance method has

  • If there is a (sorbet) sig written for the instance method, it generates a matching sig for the mailing action method
  • If not, all the params in the mailing action method will be T.untyped.
  • For return type though, the mailing action method will return ActionMailer::MessageDelivery instead of the return type of the instance method.

Jobs

This Rake task generates RBI files for all jobs classes in the Rails application (all descendants of ActiveJob::Base).

bash
❯ bundle exec rake rails_rbi:jobs

It will generate perform_later and perform_now methods for the job classes matching the signature of the perform method of the job. If there is a (sorbet) sig written for perform, it will use the same sig for perform_* methods.

Runtime Features

In addition to features provided by the static generator, sorbet-rails can provide additional features when required. This is why the installation instructions specify that sorbet-rails should be placed in the :default group of the Gemfile, not a specific environment group (eg. development only).

  • Model: The gem provides some helper method to a model to make type-checking easier:

    • find_n, first_n, last_n
    • where_missing
    • pluck_to_tstruct
    • typed_enum
  • Model Relation:

    • Make relation classes public. By default, relation classes like User::ActiveRecord_Relation, User::ActiveRecord_AssociationRelation are private
    • Add type alias, eg Model::RelationType, to represents any type of relation of a model.
  • Controller: use TypedParams to convert controller parameters to a typed structure

In addition to requireing sorbet-rails, you must also run bundle exec rake rails_rbi:custom, which will produce the RBI for these runtime features.

Discussion: #211, #214

Tips & Tricks

Look for # typed: ignore files

Because Sorbet's initial setup tries to flag files at whichever typecheck level generates 0 errors, there may be files in your repository that are # typed: ignore. This is because sometimes Rails allows very dynamic code that Sorbet does not believe it can typecheck.

It is worth going through the list of files that is ignored and resolve them (and auto upgrade the types of other files; see initial setup above). Usually this will make many more files able to be typechecked.

Overriding generated signatures if needed

sorbet-rails relies on Rails reflection to generate signatures. There are features this gem doesn't support yet such as attribute custom types. The gem also doesn't know the signature of any methods you have overridden. However, it is possible to override the signatures that sorbet-rails generates.

For example, here is how to override the signature for a method in a model:

ruby
# -- app/models/model_name.rbi --

# typed: strong
class ModelName
  sig { returns(T::Hash[...]) }
  def field_name; end

  sig { params(obj: T::Hash[....]).void }
  def field_name=(obj); end
end

Replace Rails.application.routes.url_helpers

When using url helpers like _url or _path methods outside of a controller, we usually have to add include Rails.application.routes.url_helpers in the class. However, Sorbet does not allow code that includes dynamic module. Sorbet Rails provides a drop-in replacement module for the dynamic url_helpers module, called GeneratedUrlHelpers. Following code change should resolve the sorbet type-check error:

ruby
class MyClass
-  include Rails.application.routes.url_helpers
+  include GeneratedUrlHelpers
end

find, first and last

These 3 methods can either return a single nilable record or an array of records. Sorbet does not allow us to define multiple signatures for a function (except stdlib). It doesn't support defining one function signature that has varying returning value depending on the input parameter type. We opt to define the most commonly used signature for these methods, and monkey-patch new functions for the secondary use case.

In short:

  • Use find, first and last to fetch a single record.
  • Use find_n, first_n, last_n to fetch an array of records.

find_by_, _changed?, etc.

Rails supports dynamic methods based on attribute names, such as find_by_, _changed?, etc. They all have static counterparts. Instead of generating all possible dynamic methods that Rails support, we recommend to use of the static version of these methods instead (also recommended by RuboCop).

Following are the list of attribute dynamic methods and their static counterparts. The static methods have proper signatures:

  • find_by_ -> find_by()
  • find_by_! -> find_by!()
  • _changed? -> attribute_changed?()
  • _was -> attribute_was()
  • saved_change_to_? -> saved_change_to_attribute?()
  • _before_type_cast -> read_attribute_before_type_cast()
  • will_save_change_to_? -> will_save_change_to_attribute?()

after_commit and other callbacks

Consider converting after_commit callbacks to use instance method functions. Sorbet doesn't support binding an optional block with a different context. Because of this, when using a callback with a custom block, the block is evaluated in the wrong context (Class-level context). Refer to this page for a full list of callbacks available in Rails.

Before:

ruby
after_commit do ... end

After:

ruby
after_commit :after_commit
def after_commit
  ...
end

If you wanted to make these changes using Codemod, try these commands:

bash
# from methods like after_commit do  end
❯ codemod -d

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyrailssorbet

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架