# Improve this code?

**URL:** <https://forum.elixirforum.com/t/improve-this-code/48128>\
**Category:** Questions\
**Tags:** recursion, loop\
**Created:** [June 2, 2022, 1:34am UTC](https://forum.elixirforum.com/t/improve-this-code/48128 "2022-06-02T01:34:48Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![sodapopcan](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/sodapopcan/32/34668_2.png) [@sodapopcan](https://forum.elixirforum.com/u/sodapopcan)\
**Post date:** [March 3, 2023, 3:24pm UTC](https://forum.elixirforum.com/t/improve-this-code/48128/8 "2023-03-03T15:24:08Z")

</div>

This was for one of my several abandon projects so it never grew. At one point I had my personal site in LiveView until I decide to switch over to Hugo. This is what I landed on but it didn’t have time to grow. It’s based off of @al2o3cr’s first suggestion suggested along with a component. I just build up segments are two-tuples with `{segment, path}`.

As this is old code I’m not going to look over it to see if I’m embarrassed by it or not as I might not post it 🙃

```elixir

  # In a Utils module

  @doc """
  Taks a path and return a list of tuples in the form of:

    {"segment", "/path/to/segment"}

  ## Example:

    iex> segment_path("/path/to/segment")
    iex> [{"path", "/path"}, {"to", "/path/to"}, {"segement", "/path/to/segment"}]

  This is useful for making breadcrumbs.
  """
  def segment_path(path) when is_binary(path) do
    path
    |> String.split("/", trim: true)
    |> Enum.scan([""], &[&1 | &2])
    |> Enum.map(&{hd(&1), Enum.join(Enum.reverse(&1), "/")})
  end

  # In a components module

  def breadcrumbs(assigns) do
    admin_path = String.replace(assigns.current_path, ~r/\A\/admin/, "")
    breadcrumbs = segment_path(admin_path)
    breadcrumbs = [{"dashboard", ""} | breadcrumbs]

    last = List.last(breadcrumbs)

    assigns = assign(assigns, :breadcrumbs, breadcrumbs)

    ~H"""
    <div class="cursor-default">
      <%= for {name, path} <- @breadcrumbs do %>
        <span class="after:content-['/'] after:text-gray-500 last:after:content-['']">
          <%= if {name, path} == last do %>
            <%= String.capitalize(name) %>
          <% else %>
            <.redirect to={"/admin#{path}"}><%= String.capitalize(name) %></.redirect>
          <% end %>
        </span>
      <% end %>
    </div>
    """
  end

```

Ok, I did look it over. It’s a little more complex than it needs to be for a show-and-tell but the admin specific stuff is because I was only using them in the admin section. `segment_path/1` is the main thing. This was pre-verified routes and one of the reasons I was excited about them.

EDITED: Man, I really didn’t re-read this thread before posting. Sorry for the repeated context.

---

_[View the full topic](https://forum.elixirforum.com/t/improve-this-code/48128)._
