Skip to content

Instantly share code, notes, and snippets.

View TylerPachal's full-sized avatar

Tyler Pachal TylerPachal

View GitHub Profile
def join_game(user_id, game_id) do
with {:ok, user} <- Users.get(user_id),
{:ok, game} <- Games.get(game_id),
false <- Game.is_full?(game),
false <- Game.is_started?(game),
true <- User.has_permission?(user, game)
do
Game.add_user(game, user)
else
:not_found -> {:error, "User or game not found"}
with {:width, {:ok, width}} <- {:width, Map.fetch(opts, :width)},
{:height, {:ok, height}} <- {:height, Map.fetch(opts, :height)}
do
{:ok, width * height}
else
{:width, :error} -> {:error, :missing_width}
{:height, :error} -> {:error, :missing_height}
end
with {:ok, width} <- Map.fetch(opts, :width),
{:ok, height} <- Map.fetch(opts, :height)
do
{:ok, width * height}
else
:error -> {:error, :wrong_data}
end
defmodule Api do
require Record
# Wrap the Erlang Record to make the request_uri parameter easier to access
Record.defrecord :httpd, Record.extract(:mod, from_lib: "inets/include/httpd.hrl")
def child_spec(_) do
opts = [
server_name: 'Api',
server_root: '/tmp',
def init(:ok) do
children =
[
kafka_producer_spec(),
kafka_consumer_spec(),
other_thing_spec(),
Api # Start the Api from the child_spec() function defined in that module
]
end
def application do
[
extra_applications: [:logger, :inets],
mod: {MyModule, []}
]
end
# You don't always need pattern matching
is_admin = Map.get(user, "is_admin") || false
# Using match?/2 with a guard statement
user = User.find(123)
can_access = match?(%{role: r, name: "tyler"} when r in ["owner", "admin"], user)
if can_access do
# 200
else
# 403
end
# Pattern matching with Kernel.match?/2
my_bool = match?(%{foo: _, bar: _}, my_map)
# Pattern matching with a case statement
my_bool = case my_map do
%{foo: _, bar: _} -> true
_ -> false
end