I am creating a tagging system where the user will be able to select a tag to list all entries with such tag(s).
This is how I am doing it currently
<%= link tag.name, to: Routes.event_path(@conn, :index, tags: GoerWeb.Helpers.add_tag(@tags, tag.name)) %>
def add_tag(tag_list, new_tag) when is_binary(new_tag) do
case Enum.member?(String.split(tag_list, " "), new_tag) do
false ->
if tag_list == "" do
"#{new_tag}"
else
"#{new_tag} #{tag_list}"
end
true ->
tag_list
end
end
User will also be able to remove tag that they are no longer interested and the links generated will be
<%= link tag, to: Routes.event_path(@conn, :index, tags: GoerWeb.Helpers.remove_tag(@tags, tag)) %>
def remove_tag(tag_list, to_remove_tag) when is_binary(to_remove_tag) do
String.split(tag_list, " ")
|> List.delete(to_remove_tag)
|> Enum.join(" ")
end
However if there is only 1 tag left and the user removes the tag, the link generated will be
http://localhost:4000/events?tags=
instead of
http://localhost:4000/events
Of course I could do a if check to see if the tag string is empty and use
<%= link tag, to: Routes.event_path(@conn, :index %>
instead of
<%= link tag, to: Routes.event_path(@conn, :index, tags: GoerWeb.Helpers.remove_tag(@tags, tag)) %>
but is there a neater way to handle this?
Thanks!!