Elixir, Phoenix, Ash project
Got 100's of text fields spread across 20+ Ash Resources. Finally got around to enforcing some sane max_length constraints on them.
Simple prompt, "Add sane max_length constraints to all Ash Resource text fields, based on their implied meaning"
Few minutes later, it was done, and after a quick review there weren't any changes needed. Next up, add that same max_length as maxlength on the corresponding inputs fields.
Simple prompt: "Now apply those max_length constraints to the field's corresponding input boxes"
Which I thought I was going to get 100+ edits. Well, wrong. It thought for 30s or so, and ultimately made a nice simple change in one place, core_components.ex
def input(%{field: %FormField{} = field} = assigns) do
errors = if Phoenix.Component.used_input?(field), do: field.errors, else: []
assigns
|> assign(field: nil, id: assigns.id || field.id)
...
|> maybe_inject_maxlength(field)
|> input()
end
...
@maxlength_types ~w(text email tel url search textarea)
defp maybe_inject_maxlength(%{type: type, rest: rest} = assigns, field)
when type in @maxlength_types and not is_map_key(rest, :maxlength) do
case get_field_max_length(field) do
nil -> assigns
max_length -> %{assigns | rest: Map.put(rest, :maxlength, max_length)}
end
end
defp maybe_inject_maxlength(assigns, _field), do: assigns
defp get_field_max_length(%FormField{} = field) do
with %{source: %AshPhoenix.Form{resource: resource}} <- field.form,
%{constraints: constraints} when is_list(constraints) <-
Info.attribute(resource, field.field) do
Keyword.get(constraints, :max_length)
else
_ -> nil
end
end
Absolutely brilliant. I didn't even think of that. It used one of Ash's superpowers, the DSL introspection, to just make this work.
24hrs later I am still dazed. Been using ChatGPT for 2 years or so, Claude for 9 months. And this is maybe only the 3rd time that I was actually left a bit stunned. Like, either I'm losing it, or it really is just better than me.
Top comments (0)