refactor: extract helper modules to remove code duplication
This commit is contained in:
parent
36776f8e28
commit
9af7381843
3 changed files with 163 additions and 0 deletions
59
lib/mv_web/helpers/field_type_formatter.ex
Normal file
59
lib/mv_web/helpers/field_type_formatter.ex
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
defmodule MvWeb.Helpers.FieldTypeFormatter do
|
||||
@moduledoc """
|
||||
Helper functions for formatting field types for display.
|
||||
|
||||
Handles both Ash type modules (e.g., `Ash.Type.String`) and simple atoms (e.g., `:string`).
|
||||
"""
|
||||
|
||||
alias MvWeb.Translations.FieldTypes
|
||||
|
||||
@doc """
|
||||
Formats an Ash type for display.
|
||||
|
||||
Handles both Ash type modules (e.g., `Ash.Type.String`) and simple atoms (e.g., `:string`).
|
||||
|
||||
## Parameters
|
||||
|
||||
- `type` - An atom or module representing the field type
|
||||
|
||||
## Returns
|
||||
|
||||
A human-readable string representation of the type
|
||||
|
||||
## Examples
|
||||
|
||||
iex> format(:string)
|
||||
"String"
|
||||
|
||||
iex> format(Ash.Type.String)
|
||||
"String"
|
||||
|
||||
iex> format(Ash.Type.Date)
|
||||
"Date"
|
||||
"""
|
||||
@spec format(atom() | module()) :: String.t()
|
||||
def format(type) when is_atom(type) do
|
||||
type_string = to_string(type)
|
||||
|
||||
if String.contains?(type_string, "Ash.Type.") do
|
||||
type_string
|
||||
|> String.split(".")
|
||||
|> List.last()
|
||||
|> String.downcase()
|
||||
|> then(fn type_name ->
|
||||
try do
|
||||
type_atom = String.to_existing_atom(type_name)
|
||||
FieldTypes.label(type_atom)
|
||||
rescue
|
||||
ArgumentError -> FieldTypes.label(:string)
|
||||
end
|
||||
end)
|
||||
else
|
||||
FieldTypes.label(type)
|
||||
end
|
||||
end
|
||||
|
||||
def format(type) do
|
||||
to_string(type)
|
||||
end
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue