Move ban creation to `User#ban` method

This commit is contained in:
Karina Kwiatek 2022-06-26 11:00:09 +02:00 committed by Karina Kwiatek
parent e4a00ceedc
commit 94aec26588
3 changed files with 16 additions and 22 deletions

View File

@ -1,3 +1,8 @@
# frozen_string_literal: true
require "use_case/user/ban"
require "use_case/user/unban"
class User < ApplicationRecord
include User::Relationship
include User::Relationship::Follow
@ -233,21 +238,15 @@ class User < ApplicationRecord
end
# Bans a user.
# @param duration [Integer?] Ban duration
# @param duration_unit [String, nil] Unit for the <code>duration</code> parameter. Accepted units: hours, days, weeks, months
# @param reason [String] Reason for the ban. This is displayed to the user.
# @param expiry [DateTime, nil] the expiry time of the ban
# @param reason [String, nil] Reason for the ban. This is displayed to the user.
# @param banned_by [User] User who instated the ban
def ban(duration, duration_unit = 'hours', reason = nil, banned_by = nil)
if duration
expiry = duration.public_send(duration_unit)
else
expiry = nil
end
UseCase::User::Ban.call(
target_user_id: id,
expiry: expiry,
reason: reason,
source_user_id: banned_by&.id
def ban(expiry = nil, reason = nil, banned_by = nil)
::UserBan.create!(
user: self,
expires_at: expiry,
banned_by: banned_by,
reason: reason
)
end

View File

@ -15,12 +15,7 @@ module UseCase
option :reason, type: Types::Coercible::String.optional
def call
ban = ::UserBan.create!(
user: target_user,
expires_at: expiry,
banned_by: source_user,
reason: reason
)
ban = target_user.ban(expiry, reason, source_user)
if reason == REASON_SPAM
target_user.update!(

View File

@ -421,10 +421,10 @@ describe Ajax::ModerationController, :ajax_controller, type: :controller do
let(:duration_unit) { pb == '0' ? 'hours' : nil }
context "when user is already banned" do
before { target_user.ban(nil) }
before { target_user.ban }
it "unbans the user" do
expect { subject }.to change { target_user.reload.banned? }.from(true).to(false)
expect { subject }.to change { target_user.reload.banned? }.from(true).to(false)
end
include_examples "returns the expected response"