Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sorbet compatible queries #498

Merged
merged 5 commits into from
Mar 15, 2023
Merged

Sorbet compatible queries #498

merged 5 commits into from
Mar 15, 2023

Conversation

stephenbinns
Copy link
Contributor

@stephenbinns stephenbinns commented Mar 7, 2023

Including ActiveRecordQueries to your model can cause issues with type checkers such as Sorbet, this is because this technically is using a dynamic include, which is not supported by Sorbet.

e.g.

class Order < ActiveRecord::Base
  has_many :order_transitions, autosave: false
  include Statesman::Adapters::ActiveRecordQueries[transition_class: OrderTransition, initial_state: :pending]

  def state_machine
    @state_machine ||= OrderStateMachine.new(self, transition_class: OrderTransition)
  end
end

Cannot be parsed by Sorbet - https://sorbet.org/docs/adopting#step-4-fix-constant-resolution-errors

Sorbet cannot statically analyze a codebase that dynamically includes code. For example, code like this is impossible to statically analyze.
Dynamic includes must be rewritten so that all includes are constant literals.

To avoid these issues you can instead include the TypeSafeActiveRecordQueries module and pass in configuration, for example:

class Order < ActiveRecord::Base
  has_many :order_transitions, autosave: false
  include Statesman::Adapters::TypeSafeActiveRecordQueries
  configure_state_machine transition_class: OrderTransition,
                          initial_state: :pending
  def state_machine
    @state_machine ||= OrderStateMachine.new(self, transition_class: OrderTransition)
  end
end

This avoids the dynamic include issues but also retains some of the
ergomonics of that method
@stephenbinns stephenbinns force-pushed the sorbet-compatible-queries branch from d9b6aec to cc50501 Compare March 13, 2023 13:21
@stephenbinns stephenbinns marked this pull request as ready for review March 13, 2023 13:23
@stephenbinns stephenbinns merged commit a37a3b9 into master Mar 15, 2023
@stephenbinns stephenbinns deleted the sorbet-compatible-queries branch March 15, 2023 09:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants