Sha256: d042094a18c93b2c54fb5ac9622ba99a4c34d53da38fc3f44bd1fa63359449e2
Contents?: true
Size: 1.39 KB
Versions: 5
Compression:
Stored size: 1.39 KB
Contents
# frozen_string_literal: true module ActionPolicy module PerThreadCache # :nodoc: CACHE_KEY = "action_policy.per_thread_cache" class << self attr_writer :enabled def enabled?() = @enabled == true def fetch(key) return yield unless enabled? store = (Thread.current[CACHE_KEY] ||= {}) return store[key] if store.key?(key) store[key] = yield end def clear_all Thread.current[CACHE_KEY] = {} end end # Turn off by default in test env self.enabled = !(ENV["RAILS_ENV"] == "test" || ENV["RACK_ENV"] == "test") end module Behaviours # Per-thread memoization for policies. # # Used by `policy_for` to re-use policy object for records. # # NOTE: don't forget to clear thread cache with ActionPolicy::PerThreadCache.clear_all module ThreadMemoized class << self def prepended(base) base.prepend InstanceMethods end alias included prepended end module InstanceMethods # :nodoc: def policy_for(record:, **opts) __policy_thread_memoize__(record, **opts) { super(record: record, **opts) } end end def __policy_thread_memoize__(record, **options) cache_key = policy_for_cache_key(record: record, **options) ActionPolicy::PerThreadCache.fetch(cache_key) { yield } end end end end
Version data entries
5 entries across 5 versions & 1 rubygems