Sha256: 6646bdbc7eecd1e1c8469c93d9a9a0482800d224269a96426d615686221a8433

Contents?: true

Size: 1.4 KB

Versions: 13

Compression:

Stored size: 1.4 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_method :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

13 entries across 13 versions & 1 rubygems

Version Path
action_policy-0.6.9 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.6.8 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.6.7 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.6.6 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.6.5 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.6.4 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.6.3 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.6.2 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.6.1 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.6.0 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.5.7 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.5.6 lib/action_policy/behaviours/thread_memoized.rb
action_policy-0.5.5 lib/action_policy/behaviours/thread_memoized.rb