Sha256: a12aecc4852b77b9f0254310cbd1db2d2556818dd5d4d531d32984b8e1db3068

Contents?: true

Size: 1.23 KB

Versions: 13

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

module ActionPolicy
  module Behaviours
    # Per-instance memoization for policies.
    #
    # Used by `policy_for` to re-use policy object for records.
    #
    # Example:
    #
    #   include ActionPolicy::Behaviour
    #   include ActionPolicy::Memoized
    #
    #   record = User.first
    #   policy = policy_for(record)
    #   policy2 = policy_for(record)
    #
    #   policy.equal?(policy) #=> true
    #
    #   policy.equal?(policy_for(record, with: CustomPolicy)) #=> false
    module Memoized
      class << self
        def prepended(base)
          base.prepend InstanceMethods
        end

        alias_method :included, :prepended
      end

      module InstanceMethods # :nodoc:
        def policy_for(record:, **opts)
          __policy_memoize__(record, **opts) { super(record: record, **opts) }
        end
      end

      def __policy_memoize__(record, **options)
        cache_key = policy_for_cache_key(record: record, **options)

        return __policies_cache__[cache_key] if
          __policies_cache__.key?(cache_key)

        policy = yield

        __policies_cache__[cache_key] = policy
      end

      def __policies_cache__
        @__policies_cache__ ||= {}
      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/memoized.rb
action_policy-0.6.8 lib/action_policy/behaviours/memoized.rb
action_policy-0.6.7 lib/action_policy/behaviours/memoized.rb
action_policy-0.6.6 lib/action_policy/behaviours/memoized.rb
action_policy-0.6.5 lib/action_policy/behaviours/memoized.rb
action_policy-0.6.4 lib/action_policy/behaviours/memoized.rb
action_policy-0.6.3 lib/action_policy/behaviours/memoized.rb
action_policy-0.6.2 lib/action_policy/behaviours/memoized.rb
action_policy-0.6.1 lib/action_policy/behaviours/memoized.rb
action_policy-0.6.0 lib/action_policy/behaviours/memoized.rb
action_policy-0.5.7 lib/action_policy/behaviours/memoized.rb
action_policy-0.5.6 lib/action_policy/behaviours/memoized.rb
action_policy-0.5.5 lib/action_policy/behaviours/memoized.rb