-
-
Save indigoviolet/98cb5d54609859889b4811b48a1a37a0 to your computer and use it in GitHub Desktop.
fin blog embed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Contract KeywordArgs[strict: Optional[Bool], report_only: Optional[Bool]], Func[Any => Any] => Any | |
public def with_no_db(strict: true, report_only: false) | |
# No queries permitted in this block | |
mode = (strict ? :prevent_strict : :prevent_permit_override) | |
_with_db_access_mode(mode, report_only: report_only) { yield } | |
end | |
public def with_db | |
# Queries are permitted in this block when it is nested inside a | |
# non-strict with_no_db block | |
_with_db_access_mode(:allow) { yield } | |
end | |
Contract Enum[:prevent_strict, :prevent_permit_override, :allow], KeywordArgs[report_only: Optional[Bool]], Func[Any => Any] => Any | |
private def _with_db_access_mode(mode, report_only: false) | |
prev_mode = Thread.current[:db_access_mode] | |
prev_report_only = Thread.current[:db_access_report_only] | |
# We don't allow nested with_no_db blocks to downgrade | |
# strictness | |
if prev_mode == :prevent_strict && mode != :prevent_strict | |
raise 'Cannot downgrade strictness in a strict with_no_db context' | |
end | |
begin | |
Thread.current[:db_access_report_only] = report_only | |
Thread.current[:db_access_mode] = mode | |
result = yield | |
ensure | |
Thread.current[:db_access_report_only] = prev_report_only | |
Thread.current[:db_access_mode] = prev_mode | |
end | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment