Skip to content

Instantly share code, notes, and snippets.

@Kagemaru
Last active April 8, 2024 15:07
Show Gist options
  • Save Kagemaru/d9f1b72d3ddb32f7d76c48fc93e887d2 to your computer and use it in GitHub Desktop.
Save Kagemaru/d9f1b72d3ddb32f7d76c48fc93e887d2 to your computer and use it in GitHub Desktop.
Teej Settings parser
❯ iex
Erlang/OTP 26 [erts-14.2.3] [source] [64-bit] [smp:24:24] [ds:24:24:10] [async-threads:1] [jit:ns]
Interactive Elixir (1.16.2) - press Ctrl+C to exit (type h() ENTER for help)
[dev] iex [17:05 :: 1] > defmodule Settings do
[dev] ... [17:05 :: 1] > def parse(settings) do
[dev] ... [17:05 :: 1] > [
[dev] ... [17:05 :: 1] > Enum.map(~w[feature feature2]a, &{:"is_#{&1}_enabled", &1}),
[dev] ... [17:05 :: 1] > Enum.map(~w[feature3 feature4]a, &{:"is_another_#{&1}_true", &1})
[dev] ... [17:05 :: 1] > ]
[dev] ... [17:05 :: 1] > |> List.flatten()
[dev] ... [17:05 :: 1] > |> Enum.map(fn {toggle, setting} ->
[dev] ... [17:05 :: 1] > {Map.get(settings, toggle), setting, Map.get(settings, setting)}
[dev] ... [17:05 :: 1] > end)
[dev] ... [17:05 :: 1] > |> Enum.reduce(%{}, fn
[dev] ... [17:05 :: 1] > {true, key, value}, acc -> Map.put(acc, key, value)
[dev] ... [17:05 :: 1] > _, acc -> acc
[dev] ... [17:05 :: 1] > end)
[dev] ... [17:05 :: 1] > end
[dev] ... [17:05 :: 1] > end
{:module, Settings, <<...>>, {:parse, 1}}
[dev] iex [17:05 :: 2] > settings = %{
[dev] ... [17:05 :: 2] > is_feature_enabled: true,
[dev] ... [17:05 :: 2] > feature: :test,
[dev] ... [17:05 :: 2] > is_feature2_enabled: false,
[dev] ... [17:05 :: 2] > feature2: :test2,
[dev] ... [17:05 :: 2] > is_another_feature3_true: true,
[dev] ... [17:05 :: 2] > feature3: :test3,
[dev] ... [17:05 :: 2] > is_another_feature4_true: false,
[dev] ... [17:05 :: 2] > feature4: :test4
[dev] ... [17:05 :: 2] > }
%{
feature: :test,
feature2: :test2,
feature3: :test3,
feature4: :test4,
is_another_feature3_true: true,
is_another_feature4_true: false,
is_feature2_enabled: false,
is_feature_enabled: true
}
[dev] iex [17:05 :: 3] > Settings.parse(settings)
%{feature: :test, feature3: :test3}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment