Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Pundit.authorize when passing a custom cache #838

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ Layout/CaseIndentation:
Layout/FirstArrayElementIndentation:
EnforcedStyle: consistent

Layout/FirstHashElementIndentation:
EnforcedStyle: consistent

Layout/EndAlignment:
EnforcedStyleAlignWith: variable

Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion lib/pundit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions spec/pundit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions spec/support/lib/custom_cache.rb
Original file line number Diff line number Diff line change
@@ -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