how can i access data inside map in elixir

286 Views Asked by At

i have simple chat app written using phoenix framework.

i want to access some data inside the socket

this is the method im using for that

def join("room:" <> _user, _, socket) do
    IO.inspect socket
    send self(), :after_join
    {:ok, socket}
  end

it will give nice map with all the details. what is the best way to get all rooms(topic: "room:Testuser") available using this method

this is the sample result showed in console

[info] JOIN room:Testuser to PhoenixChat.RoomChannel
  Transport:  Phoenix.Transports.WebSocket
  Parameters: %{}
%Phoenix.Socket{assigns: %{user: "Testuser"}, channel: PhoenixChat.RoomChannel,
 channel_pid: #PID<0.409.0>, endpoint: PhoenixChat.Endpoint,
 handler: PhoenixChat.UserSocket, id: nil, joined: false,
 pubsub_server: PhoenixChat.PubSub, ref: nil,
 serializer: Phoenix.Transports.WebSocketSerializer, topic: "room:Testuser",
 transport: Phoenix.Transports.WebSocket, transport_name: :websocket,
 transport_pid: #PID<0.375.0>}
[info] Replied room:Testuser :ok
1

There are 1 best solutions below

1
On

The thing you are tinkering with is not map per say. It is what we usually call struct! Struct is a map with well defined fields (similar to objects you may know from other languages).

As you have already discovered when you inspect it you can read all of the key value pairs.

When you want to access field of a struct you can say struct.field. Please read tutorial on Elixir website for more information.