Skip to content

Commit ad046ca

Browse files
committed
added Flag#accessible_to class method & tests
1 parent 5badcdb commit ad046ca

3 files changed

Lines changed: 30 additions & 0 deletions

File tree

app/models/flag.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,20 @@ class Flag < ApplicationRecord
2323

2424
validate :maximum_reason_length
2525

26+
# Gets flags appropriately scoped for a given user & post
27+
# @param user [User, nil] user to check
28+
# @param post [Post] post to check
29+
# @return [ActiveRecord::Relation<Flag>]
30+
def self.accessible_to(user, post)
31+
if user&.at_least_moderator?
32+
post.flags
33+
elsif user&.can_handle_flags?
34+
post.flags.not_confidential
35+
else
36+
post.flags.none
37+
end
38+
end
39+
2640
# Checks if the flag is confidential as per its type
2741
# @return [Boolean] check result
2842
def confidential?

test/fixtures/flags.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
one:
22
reason: ABCDEF GHIJKL MNOPQR STUVWX YZ
33
post: answer_two (Post)
4+
post_flag_type: not_confidential
45
user: standard_user
56
community: sample
67

78
declined:
89
reason: Please decline it
910
post: question_one (Post)
11+
post_flag_type: not_confidential
1012
user: standard_user
1113
community: sample
1214
status: declined

test/models/flag_test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,18 @@ class FlagTest < ActiveSupport::TestCase
3030
valid = Flag.new(reason: 'my reasons are my own', **common_attributes)
3131
assert valid.valid?
3232
end
33+
34+
test 'accessible_to should correctly scope flags' do
35+
std = users(:standard_user)
36+
del = users(:deleter)
37+
mod = users(:moderator)
38+
39+
[std, del, mod].each do |user|
40+
flags = Flag.accessible_to(user, posts(:question_one))
41+
assert_equal user.same_as?(std), flags.none?
42+
end
43+
44+
assert Flag.accessible_to(mod, posts(:deleted)).any?(&:confidential?)
45+
assert_not Flag.accessible_to(del, posts(:deleted)).any?(&:confidential?)
46+
end
3347
end

0 commit comments

Comments
 (0)