A set of tools to make the Sorbet typechecker work with Ruby on Rails seamlessly.
A set of tools to make the Sorbet typechecker work with Ruby on Rails seamlessly.
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!
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.
Follow the steps here to set up the latest version of Sorbet, up to being able to run srb tc.
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.
❯ bundle install❯ 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❯ bundle exec srb rbi hidden-definitions
❯ bundle exec srb rbi suggest-typedBecause 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.
This Rake task generates RBI files for all models in the Rails application (all descendants of ActiveRecord::Base):
❯ bundle exec rake rails_rbi:modelsYou can also regenerate RBI files for specific models. To accommodate for STI, this will generate rbi for all the subclasses of the models included.
❯ bundle exec rake rails_rbi:models[ModelName,AnotherOne,...]The generation task currently creates the following signatures:
Relation classRelation, but not class methodsIt 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:
pluck_to_tstruct instead of pluckThe 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
# -- 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
endIf 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.
This Rake task generates an RBI file defining _path and _url methods for all named routes in routes.rb:
❯ bundle exec rake rails_rbi:routesThis 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.
❯ bundle exec rake rails_rbi:helpersIf you have additional modules that are included in all your helpers and you want helpers.rbi to reflect this, you can configure it:
# -- config/initializers/sorbet_rails.rb
SorbetRails.configure do |config|
config.extra_helper_includes = ['ApplicationHelper', 'Devise::Controllers::Helpers']
endThis Rake task generates RBI files for all mailer classes in the Rails application (all descendants of ActionMailer::Base)
❯ bundle exec rake rails_rbi:mailersSince 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
ActionMailer::MessageDelivery instead of the return type of the instance method.This Rake task generates RBI files for all jobs classes in the Rails application (all descendants of ActiveJob::Base).
❯ bundle exec rake rails_rbi:jobsIt 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.
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_nwhere_missingpluck_to_tstructtyped_enumModel Relation:
User::ActiveRecord_Relation, User::ActiveRecord_AssociationRelation are privateModel::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.
# typed: ignore filesBecause 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.
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:
# -- 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
endRails.application.routes.url_helpersWhen 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:
class MyClass
- include Rails.application.routes.url_helpers
+ include GeneratedUrlHelpers
endfind, first and lastThese 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:
find, first and last to fetch a single record.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 callbacksConsider 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:
after_commit do ... endAfter:
after_commit :after_commit
def after_commit
...
endIf you wanted to make these changes using Codemod, try these commands:
# from methods like after_commit do end
❯ codemod -dNo open issues yet, or sync has not completed.