Reducing some code duplication in Ash enums
I find myself defining a few enum modules in my application like this,
Would it be appropriate to move these functions that I have copied across modules into a module and then
use
the module to bring them into my enum modules?Solution:Jump to solution
I added some functions to Enum awhile back for this. Pretty sure there are some examples in the docs.
https://hexdocs.pm/ash/Ash.Type.Enum.html#module-value-labels-and-descriptions...
11 Replies
Something like this?
The reason I don't just move the functions into another module and call them from there is that there are a couple special-case enums for which the implementations of these functions need to be different.
And would this be a candidate for a behaviour?
I think the
options_for_select
functionality should be added to AshPhoenix - I'd generally err on the side of defining the labels for the enum values manuallyWhen I did that for some of my longer enums, it felt very repetitive, and more error-prone than ndefining the labels manually only for the exceptions.
how does your code allow specifying labels for the exceptions?
If
options_for_select
were added to AshPhoenix, what would it call to determine the labels?
Completely different implementation of these functions.
e.g., in my enum for NZ regions,
ahhhh I see, the order of the
use
statements matterIs that generally considered an anti-pattern?
I don't think so. it's not one I tend to use though
Solution
I added some functions to Enum awhile back for this. Pretty sure there are some examples in the docs.
https://hexdocs.pm/ash/Ash.Type.Enum.html#module-value-labels-and-descriptions
The label/1 function does the same humanize string behavior as Phoenix.Naming.humanize
These are overridable if you need to support translations.
Agree we should add something to AshPhoenix for select options.
Oh, cool! I missed those in the changelog.