have the generator return values from a list (unique)

Hi, I would like to use the generator functionality to create resources and I have a attribute with specific codes. I'm looking for a way to pass a generator that returns values from a list but does not return the same value twice in order for the unique constraint to work correctly.
1 Reply
barnabasj
barnabasjOP2y ago
I found a way to encapsulate it into a 0 arity function that I can pass to StreamData.repeatedly
def codes do
{:ok, pid} = Agent.start(fn -> @codes end)

{pid,
fn ->
case Agent.get(pid, & &1) do
[] ->
nil

[hotel_code | hotel_codes] ->
Agent.update(pid, fn _ -> hotel_codes end)
hotel_code
end
end}
end

{agent, codes} = codes()

Api.bulk_create!(
Enum.take(
Ash.Generator.action_input(Hotel, :new, Map.merge(generators(), %{codes: StreamData.repeatedly(codes)),
2
),
Hotel,
:new,
actor: @actor,
stop_on_error?: true
)

Agent.stop(agent)
def codes do
{:ok, pid} = Agent.start(fn -> @codes end)

{pid,
fn ->
case Agent.get(pid, & &1) do
[] ->
nil

[hotel_code | hotel_codes] ->
Agent.update(pid, fn _ -> hotel_codes end)
hotel_code
end
end}
end

{agent, codes} = codes()

Api.bulk_create!(
Enum.take(
Ash.Generator.action_input(Hotel, :new, Map.merge(generators(), %{codes: StreamData.repeatedly(codes)),
2
),
Hotel,
:new,
actor: @actor,
stop_on_error?: true
)

Agent.stop(agent)

Did you find this page helpful?