diff --git a/.rubocop.yml b/.rubocop.yml index 4bc466f9..a86d3184 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -39,6 +39,9 @@ Layout/CaseIndentation: Layout/FirstArrayElementIndentation: EnforcedStyle: consistent +Layout/FirstHashElementIndentation: + EnforcedStyle: consistent + Layout/EndAlignment: EnforcedStyleAlignWith: variable diff --git a/CHANGELOG.md b/CHANGELOG.md index b16cddbc..ccc36c3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Fixed + +- Using a hash as custom cache in `Pundit.authorize` now works as documented. (#838) + ## 2.4.0 (2024-08-26) ## Changed diff --git a/lib/pundit.rb b/lib/pundit.rb index a7263b39..79c0d700 100644 --- a/lib/pundit.rb +++ b/lib/pundit.rb @@ -74,7 +74,8 @@ class << self # @see Pundit::Context#authorize def authorize(user, record, query, policy_class: nil, cache: nil) context = if cache - Context.new(user: user, policy_cache: cache) + policy_cache = CacheStore::LegacyStore.new(cache) + Context.new(user: user, policy_cache: policy_cache) else Context.new(user: user) end diff --git a/spec/pundit_spec.rb b/spec/pundit_spec.rb index 65d13b77..260b5a2e 100644 --- a/spec/pundit_spec.rb +++ b/spec/pundit_spec.rb @@ -125,6 +125,18 @@ expect(Pundit.authorize(user, [:project, comment], :create?, policy_class: PublicationPolicy)).to be_truthy end end + + context "when passed an explicit cache" do + it "uses the hash assignment interface on the cache" do + custom_cache = CustomCache.new + + Pundit.authorize(user, post, :update?, cache: custom_cache) + + expect(custom_cache.to_h).to match({ + post => kind_of(PostPolicy) + }) + end + end end describe ".policy_scope" do diff --git a/spec/support/lib/custom_cache.rb b/spec/support/lib/custom_cache.rb new file mode 100644 index 00000000..85d7ccb8 --- /dev/null +++ b/spec/support/lib/custom_cache.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +class CustomCache + def initialize + @store = {} + end + + def to_h + @store + end + + def [](key) + @store[key] + end + + def []=(key, value) + @store[key] = value + end +end