Complex actor logic in expressions?

Since actors aren't constrained to be instances of ash resources, and in expressions, templates do simple get_in calls (link), it seems somewhat challenging to represent logic in expressions that relies on anything more than simple attributes on the actor. In some calculations I'm working on, I've resorted to representing this something like this:
@impl Ash.Resource.Calculation
def expression(_opts, %{actor: actor}) do
some_complex_boolean_calculation? = Ash.calculate!(actor, :some_complex_boolean_calculation)
if some_complex_boolean_calculation? do
# specific expression if true
expr(...)
else
# specific expression if false
expr(...)
end
end
@impl Ash.Resource.Calculation
def expression(_opts, %{actor: actor}) do
some_complex_boolean_calculation? = Ash.calculate!(actor, :some_complex_boolean_calculation)
if some_complex_boolean_calculation? do
# specific expression if true
expr(...)
else
# specific expression if false
expr(...)
end
end
This works OK, but feels a little clunky. I could also use fragments in the expression along with the actor ID to go full "manual" mode and do my actor calculation manually, but that loses all the benefits of having those calculations encapsulated on the resource. Is there any known advice on the best practice for handling this sort of thing?
2 Replies
Jesse Williams
Jesse WilliamsOP2w ago
Another downside of this approach is that it generates 2 DB queries. In practice it's probably fine, but I don't love that it does that
ZachDaniel
ZachDaniel2w ago
My best advice is to just preload whatever on the actor you typically need

Did you find this page helpful?