Skip to content

Instantly share code, notes, and snippets.

@Sleepful
Last active November 18, 2022 22:32
Show Gist options
  • Save Sleepful/de79105d0670d4f5ef3875faf4c8f6d2 to your computer and use it in GitHub Desktop.
Save Sleepful/de79105d0670d4f5ef3875faf4c8f6d2 to your computer and use it in GitHub Desktop.
defmodule Fheads do
defp set_required(set, :built, :new), do: set
defp set_required(set, :built, :submit) do
type = get_field(set, :type)
assoc = get_field(set, type)
put_assoc(set, type, required: assoc.required)
end
# Re-usable outside of a changeset! :D
# (I can use this to parse structs that don't need a changeset)
def put_required(cat) do
type = Map.get(cat, :type)
if type == nil do
raise("Cannot put_required on a %Category{} without a :type field available")
end
assoc = Map.get(cat, type)
name =
case assoc.required do
true -> "Yes"
false -> "No"
nil -> "?"
end
cat
|> Map.put(:required, assoc.required)
|> Map.put(:required_name, name)
end
defp set_required(set, :loaded, :new) do
cat = put_required(set.data)
put_in(set.data, cat)
end
defp set_required(set, :loaded, :submit) do
type = get_field(set, :type)
required = get_field(set, :required)
assoc = get_field(set, type, nil)
if get_change(set, :type),
do: raise("Updating the type of a %Category{} is not allowed, changeset: #{inspect(set)}")
assoc_change = change(assoc, %{required: required})
put_change(set, type, assoc_change)
end
defp set_required(%{valid?: false} = set), do: set
defp set_required(%{valid?: true} = set) do
state = get_field(set, :__meta__).state
IO.inspect(state)
stage = set.stage
set_required(set, state, stage)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment