Initialize the GenServer State
Learn how to initialize the GenServer state.
We'll cover the following
GenServer
in the game.ex
module
Until now, we’ve relied directly on the built-in start_link/3
function from GenServer
to start new processes. However, we can do better.
When we run GenServer.start_link(Game, <initial state>)
, the idea that we’re starting a new game process is buried in the arguments. It would be much clearer if we could bring the Game
module out front by writing Game.start_link(<initial state>)
.
To do this, we follow the GenServer
pattern and define a public function that wraps a GenServer
module function. This module function then triggers a callback.
Let’s start with a public start_link/1
function in the Game
module and have it wrap the GenServer.start_link/3
function. One player will start the game and the second will join later. Let’s have Game.start_link/1
take the first player’s name in order to help build the state we need.
While we’re at it, we add a guard to make sure the name is a string:
def start_link(name) when is_binary(name), do:
GenServer.start_link(__MODULE__, name, [])
We use __MODULE__
—a macro that returns the name of the current module—instead of hard-coding the module name. This avoids errors if we ever change the module name.
GenServer
uses the middle argument, in this case, the name, as the only argument to the init/1
callback that GenServer.start_link/3
triggers.
The third argument is an optional list of options. We’ll take advantage of it later when we name GenServer
processes.
Note: This public function has greater significance than its single line might suggest. This is the beginning of the public interface for a game. It allows other processes to programmatically start new game processes.
Currently, we’ve built two-thirds of the GenServer
pattern, the public function and the GenServer
module function. The remaining part is the init/1
callback. Let’s define that next.
We’ll be working with some new modules in this function. We alias them upfront:
alias IslandsEngine.{Board, Guesses, Rules}
Get hands-on with 1200+ tech skills courses.