Skip to content

Instantly share code, notes, and snippets.

@marinho10
marinho10 / UserSocket.ex
Last active March 9, 2018 15:16
UserSocket
defmodule SuperSlimeGameWeb.UserSocket do
use Phoenix.Socket
## Channels
## Define game channel
channel("game:*", SuperSlimeGameWeb.GameChannel)
## Transports - long polling
transport(:websocket, Phoenix.Transports.WebSocket)
@marinho10
marinho10 / GameChannel.ex
Created March 9, 2018 15:17
GameChannel
defmodule SuperSlimeGameWeb.GameChannel do
use SuperSlimeGameWeb, :channel
alias SuperSlimeGame.GameState
alias SuperSlimeGame.Error
# join to topic game:*
def join("game:" <> code, %{"email" => email}, socket) do
case Map.has_key?(GameState.games(), code) do
true ->
@marinho10
marinho10 / GameState.ex
Created March 9, 2018 15:23
GameState Agent
defmodule SuperSlimeGame.GameState do
@moduledoc """
This module holds the game current state. It also contains the game logic.
Allows to add new players to the board, move them and detect collisions.
"""
@doc """
Used by the supervisor to start the Agent that will keep the game state persistent.
The initial value passed to the Agent is an empty map.
"""
@marinho10
marinho10 / handle_in.ex
Created March 9, 2018 15:58
handle_in in GameChannel
def handle_in("playerAction", payload, socket) do
broadcast!(socket, "playerAction", Map.put(payload, :from_player, socket.assigns.player))
{:noreply, socket}
end
@marinho10
marinho10 / application.ex
Created March 9, 2018 16:38
Application
defmodule SuperSlimeGame.Application do
use Application
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec
# Define workers and child supervisors to be supervised
children = [
@marinho10
marinho10 / default
Last active November 6, 2018 20:41
upstream phoenix {
server 127.0.0.1:4000 max_fails=5 fail_timeout=60s;
}
server {
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name <server_name>;
location / {
# First attempt to serve request as file, then
defmodule MyApp.Management.UserProject do
@moduledoc """
UserProject module
"""
use Ecto.Schema
import Ecto.Changeset
alias MyApp.Accounts.User
alias MyApp.Management.Project
def upsert_user_projects(user, project_ids) when is_list(project_ids) do
projects =
Project
|> where([project], project.id in ^project_ids)
|> Repo.all()
with {:ok, _struct} <-
user
|> User.changeset_update_projects(projects)
|> Repo.update() do
...
def MyApp.Management.Project do
...
many_to_many(
:users,
User,
join_through: "user_project",
on_replace: :delete
)
...
defmodule MyApp.Management.UserProject do
@moduledoc """
UserProject module
"""
use Ecto.Schema
import Ecto.Changeset
alias MyApp.Accounts.User
alias MyApp.Management.Project