I have a collection named Testbeds and various keys on this collection. Some of these are named hardware,name,status,database etc.
In a Live View , in the DOM I iterate through Testbeds and render content assigned to the various collections.
def render(assigns) do
<div>
<%= for testbed <- @testbeds do %>
# Each test bed is displayed with the different collection values
<% end %>
</div>
My problem is , I wrote a function to sort the testbeds based on a given collection but when I try to abstract it so I can use it with the DOM I get unpredictable sorting behavior,
The function as-is works but the collection properties are hard coded.
Example (this works)
def handle_event("sort_by_string", %{"field" => field}, socket) do
if socket.assigns[:sort_by_name_ascending] == false do
sorted_testbeds = Enum.sort_by(socket.assigns.testbeds, fn item -> Map.get(item, :hardware) end) #hardware is hard coded as an atom
{:noreply, assign(socket, testbeds: sorted_testbeds, sort_by_name_ascending: true)}
else
sorted_testbeds = Enum.sort_by(socket.assigns.testbeds, fn item -> Map.get(item, :hardware) end) |> Enum.reverse() #hardware is hard coded as an atom
dbg(sorted_testbeds)
{:noreply, assign(socket, testbeds: sorted_testbeds, sort_by_name_ascending: false)}
end
end
When I replace :hardware with a string it doesn’t “work”. I expect it to sort alphabetically and when :hardware is set as an atom it works as expected. When replaced as a string I get something else.
My goal is to be able to abstract the function so I can attached it to an element and sort by any collection.
<th scope="col" class="px-6 rounded-l-full " phx-click="sort_by_string" phx-value-field="hardware" >Hardware</th>