I'm confused about "assigns" what does it do?

Imagine you want to pass some value from your join function in channels to handle_in. You cannot simply assign to a variable:

def join(..., socket) do
  username = "hello"
  {:ok, socket}
end

def handle_in(..., socket) do
  username #=> this will raise
end

So instead, we store it in a data-structure (or assign it to a data structure) and pass the data structure forward:

def join(..., socket) do
  socket = assign(socket, :username, "hello")
  {:ok, socket}
end

def handle_in(..., socket) do
  socket.assigns.username #=> this works
end

The field in itself is a map with atom keys and the stored values.

18 Likes