From 410d9b5d8ee5e2587d62ada37533479a0569bfe9 Mon Sep 17 00:00:00 2001 From: Karina Kwiatek Date: Tue, 7 Feb 2023 08:36:29 +0100 Subject: [PATCH] Implement unpinning answers --- app/controllers/answer_controller.rb | 10 +++++++++ app/views/actions/_pin.html.haml | 2 +- config/routes.rb | 1 + lib/use_case/answer/unpin.rb | 33 ++++++++++++++++++++++++++++ 4 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 lib/use_case/answer/unpin.rb diff --git a/app/controllers/answer_controller.rb b/app/controllers/answer_controller.rb index 33057ceb..aaa5f07b 100644 --- a/app/controllers/answer_controller.rb +++ b/app/controllers/answer_controller.rb @@ -28,4 +28,14 @@ class AnswerController < ApplicationController format.turbo_stream { render "pin", locals: { answer: } } end end + + def unpin + answer = Answer.includes(:user).find(params[:id]) + UseCase::Answer::Unpin.call(user: current_user, answer:) + + respond_to do |format| + format.html { redirect_to(user_path(username: current_user.screen_name)) } + format.turbo_stream { render "pin", locals: { answer: } } + end + end end diff --git a/app/views/actions/_pin.html.haml b/app/views/actions/_pin.html.haml index aae54317..c6d6c4bc 100644 --- a/app/views/actions/_pin.html.haml +++ b/app/views/actions/_pin.html.haml @@ -1,5 +1,5 @@ - if answer.pinned? - = button_to pin_answer_path(id: answer.id), + = button_to unpin_answer_path(id: answer.id), class: "dropdown-item", method: :delete, form: { id: "ab-pin-#{answer.id}", data: { turbo_stream: true } } do diff --git a/config/routes.rb b/config/routes.rb index c8a12365..744a8d83 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -147,6 +147,7 @@ Rails.application.routes.draw do get "/@:username", to: "user#show", as: :user get "/@:username/a/:id", to: "answer#show", as: :answer post "/@:username/a/:id/pin", to: "answer#pin", as: :pin_answer + delete "/@:username/a/:id/pin", to: "answer#unpin", as: :unpin_answer get "/@:username/q/:id", to: "question#show", as: :question get "/@:username/followers", to: "user#followers", as: :show_user_followers get "/@:username/followings", to: "user#followings", as: :show_user_followings diff --git a/lib/use_case/answer/unpin.rb b/lib/use_case/answer/unpin.rb new file mode 100644 index 00000000..ac945e63 --- /dev/null +++ b/lib/use_case/answer/unpin.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +module UseCase + module Answer + class Unpin < UseCase::Base + option :user, type: Types.Instance(::User) + option :answer, type: Types.Instance(::Answer) + + def call + check_ownership! + check_pinned! + + answer.pinned_at = nil + answer.save! + + { + status: 200, + resource: nil + } + end + + private + + def check_ownership! + raise ::Errors::NotAuthorized unless answer.user == user + end + + def check_pinned! + raise ::Errors::BadRequest if answer.pinned_at.nil? + end + end + end +end