如何使用 Sorbet 处理 nil 值的记忆?
How to handle memoization with nil values with Sorbet?
我有这个方法:
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
因为这个文件是 typed: strict
,我需要声明 @current_organization
,但这意味着检查 defined?
总是正确的。处理 nil
这样的方法的正确模式是什么
您必须在检查 defined?
之后声明 @current_organization
,这可以在 find_by
调用
上方完成
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
示例 sorbet.run
我有这个方法:
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
因为这个文件是 typed: strict
,我需要声明 @current_organization
,但这意味着检查 defined?
总是正确的。处理 nil
这样的方法的正确模式是什么
您必须在检查 defined?
之后声明 @current_organization
,这可以在 find_by
调用
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
示例 sorbet.run