From 94aec265881012c0fd3e7494860b2612d0c6a03c Mon Sep 17 00:00:00 2001 From: Karina Kwiatek Date: Sun, 26 Jun 2022 11:00:09 +0200 Subject: [PATCH] Move ban creation to `User#ban` method --- app/models/user.rb | 27 +++++++++---------- lib/use_case/user/ban.rb | 7 +---- .../ajax/moderation_controller_spec.rb | 4 +-- 3 files changed, 16 insertions(+), 22 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 751f7c9e..54dc890b 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -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 duration 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 diff --git a/lib/use_case/user/ban.rb b/lib/use_case/user/ban.rb index 5ba61f40..ad032ef8 100644 --- a/lib/use_case/user/ban.rb +++ b/lib/use_case/user/ban.rb @@ -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!( diff --git a/spec/controllers/ajax/moderation_controller_spec.rb b/spec/controllers/ajax/moderation_controller_spec.rb index 265a1308..8aa00bab 100644 --- a/spec/controllers/ajax/moderation_controller_spec.rb +++ b/spec/controllers/ajax/moderation_controller_spec.rb @@ -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"