Ash FrameworkAF
Ash Framework5mo ago
17 replies
aidalgol

Reducing some code duplication in Ash enums

I find myself defining a few enum modules in my application like this,
defmodule MyApp.MyDomain.SomeEnum do
  use Ash.Type.Enum, values: [:foo, :bar, :blah]

  def label_for(category) do
    category
    |> Atom.to_string()
    |> String.capitalize()
  end

  @doc """
  Returns a list suitable for passing to `MyAppWeb.CoreComponents.input/1` when
  `type=select`.
  """
  def options_for_select do
    for category <- values() do
      {label_for(category), category}
    end
  end
end

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
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
Was this page helpful?