Use a policy for pinning/unpinning

This commit is contained in:
Karina Kwiatek 2023-02-10 11:34:55 +01:00
parent 2d6ff76461
commit 736ca4d6b0
4 changed files with 22 additions and 10 deletions

View File

@ -0,0 +1,14 @@
# frozen_string_literal: true
class AnswerPolicy
attr_reader :user, :answer
def initialize(user, answer)
@user = user
@answer = answer
end
def pin? = answer.user == user
def unpin? = answer.user == user
end

View File

@ -7,7 +7,7 @@ module UseCase
option :answer, type: Types.Instance(::Answer)
def call
check_ownership!
authorize!(:pin, user, answer)
check_unpinned!
answer.pinned_at = Time.now.utc
@ -21,10 +21,6 @@ module UseCase
private
def check_ownership!
raise ::Errors::NotAuthorized unless answer.user == user
end
def check_unpinned!
raise ::Errors::BadRequest if answer.pinned_at.present?
end

View File

@ -7,7 +7,7 @@ module UseCase
option :answer, type: Types.Instance(::Answer)
def call
check_ownership!
authorize!(:unpin, user, answer)
check_pinned!
answer.pinned_at = nil
@ -21,10 +21,6 @@ module UseCase
private
def check_ownership!
raise ::Errors::NotAuthorized unless answer.user == user
end
def check_pinned!
raise ::Errors::BadRequest if answer.pinned_at.nil?
end

View File

@ -9,5 +9,11 @@ module UseCase
def self.call(...) = new(...).call
def call = raise NotImplementedError
private
def authorize!(verb, user, record, error_class: Errors::NotAuthorized)
raise error_class unless Pundit.policy!(user, record).public_send("#{verb}?")
end
end
end