mirror of
https://github.com/discourse/discourse.git
synced 2025-02-02 23:27:15 +08:00
fc1c5f6a8d
Currently in services, the `contract` step is only used to define where the contract will be called in the execution flow. Then, a `Contract` class has to be defined with validations in it. This patch allows the `contract` step to take a block containing validations, attributes, etc. directly. No need to then open a `Contract` class later in the service. It also has a nice side effect, as it’s now easy to define multiples contracts inside the same service. Before, we had the `class_name:` option, but it wasn’t really useful as you had to redefine a complete new contract class. Now, when using a name for the contract other than `default`, a new contract will be created automatically using the provided name. Example: ```ruby contract(:user) do attribute :user_id, :integer validates :user_id, presence: true end ``` This will create a `UserContract` class and use it, also putting the resulting contract in `context[:user_contract]`.
59 lines
1.3 KiB
Ruby
59 lines
1.3 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
VALID_DIRECTIONS = %w[up down]
|
|
|
|
class Flags::ReorderFlag
|
|
include Service::Base
|
|
|
|
contract do
|
|
attribute :flag_id, :integer
|
|
attribute :direction, :string
|
|
|
|
validates :flag_id, presence: true
|
|
validates :direction, inclusion: { in: VALID_DIRECTIONS }
|
|
end
|
|
model :flag
|
|
policy :invalid_access
|
|
policy :invalid_move
|
|
transaction do
|
|
step :move
|
|
step :log
|
|
end
|
|
|
|
private
|
|
|
|
def fetch_flag(flag_id:)
|
|
Flag.find(flag_id)
|
|
end
|
|
|
|
def invalid_access(guardian:, flag:)
|
|
guardian.can_reorder_flag?(flag)
|
|
end
|
|
|
|
def all_flags
|
|
@all_flags ||= Flag.where.not(name_key: "notify_user").order(:position)
|
|
end
|
|
|
|
def invalid_move(flag:, direction:)
|
|
return false if all_flags.first == flag && direction == "up"
|
|
return false if all_flags.last == flag && direction == "down"
|
|
true
|
|
end
|
|
|
|
def move(flag:, direction:)
|
|
old_position = flag.position
|
|
index = all_flags.index(flag)
|
|
target_flag = all_flags[direction == "up" ? index - 1 : index + 1]
|
|
|
|
flag.update!(position: target_flag.position)
|
|
target_flag.update!(position: old_position)
|
|
end
|
|
|
|
def log(guardian:, flag:, direction:)
|
|
StaffActionLogger.new(guardian.user).log_custom(
|
|
"move_flag",
|
|
{ flag: flag.name, direction: direction },
|
|
)
|
|
end
|
|
end
|