Skip to content

4. Mostrar matches

Jorge Bejar edited this page Nov 10, 2022 · 11 revisions

El objetivo de esta parte es listar los matches que se jugarán en el grupo.

Creación y listado de matches

Al igual que para los teams, creamos el archivo match.ex dentro de la carpeta fixture con el siguiente contenido:

defmodule WorldCup.Fixture.Match do
  defstruct [
    :id,
    :home_team,
    :away_team,
    :round,
    played: false
  ]
end

Por otro lado, agregamos la función para listar los matches dentro del contexto fixture.ex.

defmodule WorldCup.Fixture do
  ... 
- alias WorldCup.Fixture.Team
+ alias WorldCup.Fixture.{Match, Team}

  ...

  @teams [@uru_team, @kor_team, @por_team, @gha_team]

  # ATENCIÓN
  # Hay que agregar esta lista de matches, que no aparece como parte del diff
  # para facilitar el copy-paste.

  @matches [
    %Match{
      id: "match_1",
      home_team: @uru_team,
      away_team: @kor_team,
      round: "round_1"
    },
    %Match{
      id: "match_2",
      home_team: @por_team,
      away_team: @gha_team,
      round: "round_1"
    },
    %Match{
      id: "match_3",
      home_team: @uru_team,
      away_team: @gha_team,
      round: "round_2"
    },
    %Match{
      id: "match_4",
      home_team: @por_team,
      away_team: @kor_team,
      round: "round_2"
    },
    %Match{
      id: "match_5",
      home_team: @uru_team,
      away_team: @por_team,
      round: "round_3"
    },
    %Match{
      id: "match_6",
      home_team: @gha_team,
      away_team: @kor_team,
      round: "round_3"
    }
  ]

  def list_teams(), do: @teams
+ def list_matches(), do: @matches
end

Por último, agregamos la variable matches a los assigns del socket en nuestra live view, y los listamos en el render:

defmodule WorldCupWeb.ForecastLive do
  
  ...

  def mount(_params, _session, socket) do
    teams = Fixture.list_teams()
-   socket = assign(socket, :teams, teams)
+   matches = Fixture.list_matches()

+   socket =
+     socket
+     |> assign(:teams, teams)
+     |> assign(:matches, matches)

    {:ok, socket}
  end

  ...

        </tbody>
      </table>

+     <div class="rounds">
+       <%= for match <- @matches do %>
+         <div>
+           <%= match.home_team.name %> vs <%= match.away_team.name %>
+         </div>
+       <% end %>
+     </div>
    """
  end
end

Si todos los pasos se llevaron a cabo de manera satisfactoria, visitando http://localhost:4000/forecast deberíamos ver lo siguiente:

Welcome page

Commit en Git

git add -A
git commit -m "Mostrar matches"

Check Point


Si se necesita "ponerse al día" con los pasos hasta este punto ejecutar los siguientes comandos:

# Agregar el remote si no se hizo antes
git remote add origin https://github.com/wyeworks/elixirconf-workshop-2022.git
git fetch origin

git reset --hard b7c70030

Siguiente: 5. Escribiendo componentes