Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using agents as an abstraction around states


The Agent module provides a basic server implementation and is a convenient way to spawn a process that needs to maintain a state. Agents in Elixir provide an intuitive API to update and retrieve the state.

In this recipe, we will create a module, phone_book.ex, where we will be able to store and retrieve data.

How to do it…

To create our phone book using an agent to maintain states, follow these steps:

  1. Open your code editor and create a file named phone_book.ex.

  2. Add the following code to the file you created:

    defmodule PhoneBook do
    
      @name __MODULE__
    
      def start_link do
        Agent.start_link(fn -> %{} end, name: @name)
      end
    
      def insert(user, number) do
        Agent.update(@name, &Map.put(&1, user, number))
      end
    
      def get(user) do
        Agent.get(@name, &Map.get(&1, user))
      end
    
    end
  3. Start IEx and load the module:

    > iex phone_book.ex
    
  4. Start the process that will hold our phone book data:

    iex(1)> PhoneBook.start_link
    {:ok, #PID...