Use a policy for pinning/unpinning
This commit is contained in:
parent
2d6ff76461
commit
736ca4d6b0
|
@ -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
|
|
@ -7,7 +7,7 @@ module UseCase
|
||||||
option :answer, type: Types.Instance(::Answer)
|
option :answer, type: Types.Instance(::Answer)
|
||||||
|
|
||||||
def call
|
def call
|
||||||
check_ownership!
|
authorize!(:pin, user, answer)
|
||||||
check_unpinned!
|
check_unpinned!
|
||||||
|
|
||||||
answer.pinned_at = Time.now.utc
|
answer.pinned_at = Time.now.utc
|
||||||
|
@ -21,10 +21,6 @@ module UseCase
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def check_ownership!
|
|
||||||
raise ::Errors::NotAuthorized unless answer.user == user
|
|
||||||
end
|
|
||||||
|
|
||||||
def check_unpinned!
|
def check_unpinned!
|
||||||
raise ::Errors::BadRequest if answer.pinned_at.present?
|
raise ::Errors::BadRequest if answer.pinned_at.present?
|
||||||
end
|
end
|
||||||
|
|
|
@ -7,7 +7,7 @@ module UseCase
|
||||||
option :answer, type: Types.Instance(::Answer)
|
option :answer, type: Types.Instance(::Answer)
|
||||||
|
|
||||||
def call
|
def call
|
||||||
check_ownership!
|
authorize!(:unpin, user, answer)
|
||||||
check_pinned!
|
check_pinned!
|
||||||
|
|
||||||
answer.pinned_at = nil
|
answer.pinned_at = nil
|
||||||
|
@ -21,10 +21,6 @@ module UseCase
|
||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
def check_ownership!
|
|
||||||
raise ::Errors::NotAuthorized unless answer.user == user
|
|
||||||
end
|
|
||||||
|
|
||||||
def check_pinned!
|
def check_pinned!
|
||||||
raise ::Errors::BadRequest if answer.pinned_at.nil?
|
raise ::Errors::BadRequest if answer.pinned_at.nil?
|
||||||
end
|
end
|
||||||
|
|
|
@ -9,5 +9,11 @@ module UseCase
|
||||||
def self.call(...) = new(...).call
|
def self.call(...) = new(...).call
|
||||||
|
|
||||||
def call = raise NotImplementedError
|
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
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in New Issue