Event changeset more cleaner

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2018-12-03 12:29:31 +01:00
parent dd87ad4f7e
commit c6e6a61000
No known key found for this signature in database
GPG Key ID: A061B9DDE0CA0773
2 changed files with 37 additions and 17 deletions

View File

@ -322,4 +322,13 @@ defmodule Mobilizon.Actors.Actor do
|> Enum.map(& &1.actor_id)
|> Enum.member?(follower_actor_id)
end
@spec actor_acct_from_actor(struct()) :: String.t()
def actor_acct_from_actor(%Actor{preferred_username: preferred_username, domain: domain}) do
if is_nil(domain) do
preferred_username
else
"#{preferred_username}@#{domain}"
end
end
end

View File

@ -45,21 +45,6 @@ defmodule Mobilizon.Events.Event do
@doc false
def changeset(%Event{} = event, attrs) do
# TODO : Change all of this
actor_url =
if Map.has_key?(attrs, :organizer_actor) do
attrs.organizer_actor.preferred_username
else
""
end
uuid = Ecto.UUID.generate()
url =
if Map.has_key?(attrs, "url"),
do: attrs["url"],
else: "#{MobilizonWeb.Endpoint.url()}/@#{actor_url}/#{uuid}"
event
|> Ecto.Changeset.cast(attrs, [
:title,
@ -81,8 +66,7 @@ defmodule Mobilizon.Events.Event do
])
|> cast_assoc(:tags)
|> cast_assoc(:physical_address)
|> put_change(:uuid, uuid)
|> put_change(:url, url)
|> build_url()
|> validate_required([
:title,
:begins_on,
@ -93,4 +77,31 @@ defmodule Mobilizon.Events.Event do
:address_type
])
end
@spec build_url(Ecto.Changeset.t()) :: Ecto.Changeset.t()
defp build_url(%Ecto.Changeset{changes: %{url: _url}} = changeset), do: changeset
defp build_url(%Ecto.Changeset{changes: %{organizer_actor: organizer_actor}} = changeset) do
organizer_actor
|> Actor.actor_acct_from_actor()
|> do_build_url(changeset)
end
defp build_url(%Ecto.Changeset{changes: %{organizer_actor_id: organizer_actor_id}} = changeset) do
organizer_actor_id
|> Mobilizon.Actors.get_actor!()
|> Actor.actor_acct_from_actor()
|> do_build_url(changeset)
end
defp build_url(%Ecto.Changeset{} = changeset), do: changeset
@spec do_build_url(String.t(), Ecto.Changeset.t()) :: Ecto.Changeset.t()
defp do_build_url(actor_acct, changeset) do
uuid = Ecto.UUID.generate()
changeset
|> put_change(:uuid, uuid)
|> put_change(:url, "#{MobilizonWeb.Endpoint.url()}/@#{actor_acct}/#{uuid}")
end
end