mirror of
https://github.com/discourse/discourse.git
synced 2024-12-14 14:38:33 +08:00
584424594e
This patch replaces the parameters provided to a service through `params` by the contract object. That way, it allows better consistency when accessing input params. For example, if you have a service without a contract, to access a parameter, you need to use `params[:my_parameter]`. But with a contract, you do this through `contract.my_parameter`. Now, with this patch, you’ll be able to access it through `params.my_parameter` or `params[:my_parameter]`. Some methods have been added to the contract object to better mimic a Hash. That way, when accessing/using `params`, you don’t have to think too much about it: - `params.my_key` is also accessible through `params[:my_key]`. - `params.my_key = value` can also be done through `params[:my_key] = value`. - `#slice` and `#merge` are available. - `#to_hash` has been implemented, so the contract object will be automatically cast as a hash by Ruby depending on the context. For example, with an AR model, you can do this: `user.update(**params)`.
59 lines
1.3 KiB
Ruby
59 lines
1.3 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
class Flags::CreateFlag
|
|
include Service::Base
|
|
|
|
policy :invalid_access
|
|
params do
|
|
attribute :name, :string
|
|
attribute :description, :string
|
|
attribute :require_message, :boolean
|
|
attribute :enabled, :boolean
|
|
attribute :applies_to
|
|
attribute :auto_action_type, :boolean
|
|
|
|
validates :name, presence: true
|
|
validates :description, presence: true
|
|
validates :name, length: { maximum: Flag::MAX_NAME_LENGTH }
|
|
validates :description, length: { maximum: Flag::MAX_DESCRIPTION_LENGTH }
|
|
validates :applies_to, inclusion: { in: -> { Flag.valid_applies_to_types } }, allow_nil: false
|
|
end
|
|
policy :unique_name
|
|
model :flag, :instantiate_flag
|
|
transaction do
|
|
step :create
|
|
step :log
|
|
end
|
|
|
|
private
|
|
|
|
def invalid_access(guardian:)
|
|
guardian.can_create_flag?
|
|
end
|
|
|
|
def unique_name(params:)
|
|
!Flag.custom.where(name: params[:name]).exists?
|
|
end
|
|
|
|
def instantiate_flag(params:)
|
|
Flag.new(params.merge(notify_type: true))
|
|
end
|
|
|
|
def create(flag:)
|
|
flag.save!
|
|
end
|
|
|
|
def log(guardian:, flag:)
|
|
StaffActionLogger.new(guardian.user).log_custom(
|
|
"create_flag",
|
|
{
|
|
name: flag.name,
|
|
description: flag.description,
|
|
applies_to: flag.applies_to,
|
|
require_message: flag.require_message,
|
|
enabled: flag.enabled,
|
|
},
|
|
)
|
|
end
|
|
end
|