Skip to content

Commit 20d68de

Browse files
committed
docs: improve optional and nillable context examples
1 parent be24d1d commit 20d68de

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

docs/authorization_context.md

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,26 @@ end
1818

1919
Now you must provide `account` during policy initialization. When authorization key is missing or equals to `nil`, `ActionPolicy::AuthorizationContextMissing` error is raised.
2020

21-
**NOTE:** if you want to allow passing `nil` as `account` value, you must add `allow_nil: true` option to `authorize`.
22-
If you want to be able not to pass `account` at all, you must add `optional: true`
21+
If you want to allow passing `nil` as `account` value, you must add `allow_nil: true` option to `authorize`.
22+
If you want to be able not to pass `account` at all, you must add `optional: true`:
23+
24+
```ruby
25+
class GuestPolicy < ApplicationPolicy
26+
# With allow_nil: true, the `user` key is still required to be present
27+
# in the authorization context
28+
authorize :user, allow_nil: true
29+
end
30+
31+
class ProjectPolicy < ApplicationPolicy
32+
# With optional: true, authorization context may not include the `user` key at all
33+
authorize :team, optional: true
34+
end
35+
36+
GuestPolicy.new(user: nil) #=> OK
37+
GuestPolicy.new #=> raises ActionPolicy::AuthorizationContextMissing
38+
39+
ProjectPolicy.new(user: user) #=> OK
40+
```
2341

2442
To do that automatically in your `authorize!` and `allowed_to?` calls, you must also configure authorization context. For example, in your controller:
2543

lefthook.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ pre-commit:
1515
rubocop:
1616
tags: style
1717
glob: "**/*.md"
18-
run: BUNDLE_GEMFILE=gemfiles/rubocop.gemfile bundle exec rubocop {staged_files}
18+
run: BUNDLE_GEMFILE=gemfiles/rubocop.gemfile bundle exec rubocop -c .rubocop-md.yml {staged_files}

0 commit comments

Comments
 (0)