Skip to content

Instantly share code, notes, and snippets.

View TylerPachal's full-sized avatar

Tyler Pachal TylerPachal

View GitHub Profile
@TylerPachal
TylerPachal / flow_supervisor_test.exs
Created November 25, 2017 16:21
This an example of how a runtime exception inside of a flow sends a :normal exit message
# This an example of how a runtime exception inside of a flow
# sends a :normal exit message.
#
# To run this code add the Flow dependency to the mix.exs file:
# {:flow, "~> 0.11"}
#
# The behaviour that I get is the stacktrace is printed to STDOUT,
# and the flush() function outputs a message like this:
# {:EXIT, #PID<0.144.0>, :normal}
# But I am expecting a non-normal exit message.
# Pattern matching with a case statement
my_bool = case my_map do
%{foo: _, bar: _} -> true
_ -> false
end
# Pattern matching with Kernel.match?/2
my_bool = match?(%{foo: _, bar: _}, my_map)
# 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
# You don't always need pattern matching
is_admin = Map.get(user, "is_admin") || false
def application do
[
extra_applications: [:logger, :inets],
mod: {MyModule, []}
]
end
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
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',
with {:ok, width} <- Map.fetch(opts, :width),
{:ok, height} <- Map.fetch(opts, :height)
do
{:ok, width * height}
else
:error -> {:error, :wrong_data}
end
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