2024-05-29 12:39:58 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2024-07-03 06:45:37 +08:00
|
|
|
class Flags::ToggleFlag
|
2024-05-29 12:39:58 +08:00
|
|
|
include Service::Base
|
|
|
|
|
DEV: Have `contract` take a block in services
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]`.
2024-10-01 23:17:14 +08:00
|
|
|
contract do
|
|
|
|
attribute :flag_id, :integer
|
|
|
|
|
|
|
|
validates :flag_id, presence: true
|
|
|
|
end
|
2024-05-29 12:39:58 +08:00
|
|
|
model :flag
|
|
|
|
policy :invalid_access
|
|
|
|
transaction do
|
|
|
|
step :toggle
|
|
|
|
step :log
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def fetch_flag(flag_id:)
|
|
|
|
Flag.find(flag_id)
|
|
|
|
end
|
|
|
|
|
|
|
|
def invalid_access(guardian:)
|
|
|
|
guardian.can_toggle_flag?
|
|
|
|
end
|
|
|
|
|
|
|
|
def toggle(flag:)
|
|
|
|
flag.update!(enabled: !flag.enabled)
|
|
|
|
end
|
|
|
|
|
|
|
|
def log(guardian:, flag:)
|
|
|
|
StaffActionLogger.new(guardian.user).log_custom(
|
|
|
|
"toggle_flag",
|
|
|
|
{ flag: flag.name, enabled: flag.enabled },
|
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|