Sha256: 00d1ce1a38ec3063d5bec8a2eb909f40457ed263d079e67cbe6c4617cdf45fff
Contents?: true
Size: 1.38 KB
Versions: 4
Compression:
Stored size: 1.38 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; end 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_method :included, :prepended end module InstanceMethods # :nodoc: def policy_for(record:, **opts) __policy_thread_memoize__(record, **opts) { super } 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
4 entries across 4 versions & 1 rubygems