mirror of
https://github.com/Retrospring/retrospring.git
synced 2024-11-20 10:29:53 +01:00
Use a policy for pinning/unpinning
This commit is contained in:
parent
2d6ff76461
commit
736ca4d6b0
4 changed files with 22 additions and 10 deletions
14
app/policies/answer_policy.rb
Normal file
14
app/policies/answer_policy.rb
Normal 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
|
|
@ -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 a new issue