Skip to content

Instantly share code, notes, and snippets.

@indigoviolet
Last active December 26, 2017 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indigoviolet/98cb5d54609859889b4811b48a1a37a0 to your computer and use it in GitHub Desktop.
Save indigoviolet/98cb5d54609859889b4811b48a1a37a0 to your computer and use it in GitHub Desktop.
fin blog embed
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