Code Snippets Elixir

Short texts Elixir 🧑‍💻 Code snippets Elixir ✍️ Reading lists Elixir 👀

Elixir Simple Cache

defmodule Elixir.Cache do @moduledoc “”” Author: Nuno M. Warning: This is exploratory, not tested at all. A simple Cache system implement using ETS as a way to create in-memory cache named tables. In order to keep concurrent access to the cache tables, methods don’t use the GenServer but use the ets functions directly. Since the […]

Elvis Test

defmodule ElvisTest do use ExUnit.Case def a ~> b, do: elvis(a, b) def elvis(nil, fun), do: nil def elvis({nil, default_val}, fun), do: elvis(default_val, fun) def elvis(val, fun), do: fun.(val) test “example” do tag = fn inner, tag -> “#{inner}” end params = %{title: “Movie Title”, description: “Great Movie A+”} result_1 = params[:description] ~> fn a […]

Schedule engineering meetings from a list of people on the blockchain and a given start date

Mix.install([ {:ethereumex, “~> 0.7.0”}, {:ex_abi, “~> 0.5.2”}, {:ex_keccak, path: “../ex_keccak”, override: true} # fixed a bug locally ]) # Application.put_env(:ethereumex, :url, “https://polygon-rpc.com/”) Application.put_env(:ethereumex, :url, “https://rpc-mumbai.matic.today”) defmodule MeetingScheduler do # testnet contract address @contract_address “0x9C55AE6cB109Bded7ee8336161D0a5c90EAAB897” def generate_schedule(start_date) do start_date = Date.from_iso8601!(start_date) engineers = get_engineers() engineers |> Enum.reduce([], fn engineer, [{date, _}|_] = acc -> next_date = […]

How we use `Kernal.match/2` to validate that a list has an expected value.

# chunk of code from our tests where we validated that an expected metric was captured # heavily edited out company info metrics = capture_metrics(fn -> with_trace(fn -> assert {:ok, _result} = Work.stuff() end) end) assert Enum.any?( metrics, &match?( %{ metadata: %{ result_id: ^result_id, status: :success }, topic: “engine.work.reconcile” }, &1 ) )

Elixir Redis Lock

defmodule Toolkit.RedisLock do @moduledoc “”” Provide mechanism to lock and check locking of a given key. When set lock on a key, must set expiration time to make sure no lock live forever “”” @redix_conn :octosells_cache @doc “”” Lock given key for `lock_duration` in second. Default lock duration is 5 minute This function make sure […]