improvement: add add_bypass and add_policy igniter utilities

This commit is contained in:
Zach Daniel 2024-09-06 15:14:59 -04:00
parent c23db26380
commit e148dda41e

View file

@ -47,6 +47,64 @@ defmodule Ash.Resource.Igniter do
[Ash.Resource | List.wrap(Application.get_env(app_name, :base_resources))]
end
@doc "Adds a bypass to the top of the resource's `policies` block"
def add_bypass(igniter, resource, condition, body) do
bypass =
quote do
policies do
bypass unquote(condition) do
unquote(body)
end
end
end
|> Sourceror.to_string()
|> Sourceror.parse_string!()
Igniter.Code.Module.find_and_update_module!(igniter, resource, fn zipper ->
with {:ok, zipper} <-
Igniter.Code.Function.move_to_function_call_in_current_scope(
zipper,
:policies,
1
),
{:ok, zipper} <- Igniter.Code.Common.move_to_do_block(zipper) do
{:ok, Igniter.Code.Common.add_code(zipper, bypass, :before)}
else
_ ->
{:ok, Igniter.Code.Common.add_code(zipper, bypass)}
end
end)
end
@doc "Adds a policy to the bottom of the resource's `policies` block"
def add_policy(igniter, resource, condition, body) do
policy =
quote do
policies do
policy unquote(condition) do
unquote(body)
end
end
end
|> Sourceror.to_string()
|> Sourceror.parse_string!()
Igniter.Code.Module.find_and_update_module!(igniter, resource, fn zipper ->
with {:ok, zipper} <-
Igniter.Code.Function.move_to_function_call_in_current_scope(
zipper,
:policies,
1
),
{:ok, zipper} <- Igniter.Code.Common.move_to_do_block(zipper) do
{:ok, Igniter.Code.Common.add_code(zipper, policy, :after)}
else
_ ->
{:ok, Igniter.Code.Common.add_code(zipper, policy)}
end
end)
end
@doc "Adds the given code block to the resource's `attributes` block"
def add_attribute(igniter, resource, attribute) do
Igniter.Code.Module.find_and_update_module!(igniter, resource, fn zipper ->