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