'How to handle memoization with nil values with Sorbet?
I have this method:
def current_organization
return @current_organization if defined?(@current_organization)
subdomain = request.subdomain.to_s
return @current_organization = nil if subdomain.blank?
return @current_organization = nil if Allowable::DeniedSlugs.include?(subdomain)
@current_organization = Organization.find_by(slug: subdomain)
end
Because this file is typed: strict, I need to declare @current_organization, but this would mean that checking defined? would always be true. What is the correct pattern for handling nil for methods like this
Solution 1:[1]
You will have to declare @current_organization after checking defined? which can be done just above the find_by call
def current_organization
return @current_organization if defined?(@current_organization)
...
@current_organization = T.let(@current_organization, T.nilable(Organization))
@current_organization = Organization.find_by(slug: subdomain)
end
Example on sorbet.run
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel Gilchrist |
