concept Chucky in category elixir

appears as: Chucky
The Little Elixir & OTP Guidebook

This is an excerpt from Manning's book The Little Elixir & OTP Guidebook.

Listing 9.1. Implementing the main Chucky server (lib/server.ex)
defmodule Chucky.Server do
  use GenServer
  #######
  # API #
  #######
  def start_link do
    GenServer.start_link(__MODULE__, [], [name: {:global, __MODULE__}])              #1
  end
  def fact do
    GenServer.call({:global, __MODULE__}, :fact)                                     #2
  end
  #############
  # Callbacks #
  #############
  def init([]) do
    :random.seed(:os.timestamp)
    facts = "facts.txt"
             |> File.read!
             |> String.split("\n")
    {:ok, facts}
  end
  def handle_call(:fact, _from, facts) do
    random_fact = facts 
                  |> Enum.shuffle 
                  |> List.first
    {:reply, random_fact, facts}
  end
end

Most of this code shouldn’t be hard to understand, although the usage of :global in Chucky.Server.start_link/0 and Chucky.Server.fact/1 is new. In Chucky.Server.start_link/0, you register the name of the module using {:global, __MODULE__}. This has the effect of registering Chucky.Server onto the global_name_server process. This process is started each time a node starts. This means there isn’t a single “special” node that keeps track of the name tables. Instead, each node will have a replica of the name tables.

9.2. Building Chucky

Chucky is a simple OTP application. The meat of the application lies in a GenServer. You’ll first build that, followed by implementing the Application behavior. Finally, you’ll see how to hook everything up to use failover and takeover.