Where is the right place to perform transformation on form data before database insert?

Greetings, I have a form that will contain plain text in AsciiDoc format. I would like to convert the AsciiDoc to HTML and store it alongside the original in the database. I'm having a hard time understanding where the best place to do this is. I thought it would be a good candidate for an Ash Calculation, but the examples don't seem to deal with this kind of thing, so I wondered if it was an anti-pattern. In the spirit of "try the simplest thing that will work", I could just do it in the handle_events for creating and updating the resources. Is that a decent approach? Am I overthinking it?
2 Replies
ZachDaniel
ZachDaniel3y ago
I would suggest doing it in the resource. We have a similar pattern in ash_hq to transform markdown to HTML
changes do
change before_action(fn changeset ->
text = Ash.Changeset.get_attribute(changeset, :text)
Ash.Changeset.force_change_attribute(changeset, :text_html, to_html(text))
end), where: [changing(:text)]
end
changes do
change before_action(fn changeset ->
text = Ash.Changeset.get_attribute(changeset, :text)
Ash.Changeset.force_change_attribute(changeset, :text_html, to_html(text))
end), where: [changing(:text)]
end
You can use a global change to add this behavior to any action that is changing the text attribute. and using before_action there ensures that you don't do an expensive translation on every type of the form It is shorthand for this:
changes do
change fn changeset, context ->
Ash.Changeset.before_action(changeset, fn changeset ->
text = Ash.Changeset.get_attribute(changeset, :text)
Ash.Changeset.force_change_attribute(changeset, :text_html, to_html(text))
end)
end, where: [changing(:text)]
end
changes do
change fn changeset, context ->
Ash.Changeset.before_action(changeset, fn changeset ->
text = Ash.Changeset.get_attribute(changeset, :text)
Ash.Changeset.force_change_attribute(changeset, :text_html, to_html(text))
end)
end, where: [changing(:text)]
end
cro
croOP3y ago
Great, I will try this. Thank you!

Did you find this page helpful?