Skip to content

Instantly share code, notes, and snippets.

@eteubert
Created July 20, 2018 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eteubert/8d32b404bf0d9b4f4a1482e907619911 to your computer and use it in GitHub Desktop.
Save eteubert/8d32b404bf0d9b4f4a1482e907619911 to your computer and use it in GitHub Desktop.
Elixir GenServer to render a progress bar
defmodule Some.Progress do
use GenServer
def start_link() do
GenServer.start_link(__MODULE__, %{total: 0, progress: 0}, name: __MODULE__)
end
def init(args) do
{:ok, args}
end
def start(total) do
GenServer.call(__MODULE__, {:start, total})
end
def update(progress) do
GenServer.call(__MODULE__, {:update, progress})
end
def increment() do
GenServer.call(__MODULE__, :increment)
end
def handle_call({:start, total}, _from, state) do
{:reply, render(0, total), %{state | total: total, progress: 0}}
end
def handle_call({:update, progress}, _from, state) do
{:reply, render(progress, state.total), %{state | progress: progress}}
end
def handle_call(:increment, _from, state) do
progress = state.progress + 1
{:reply, render(progress, state.total), %{state | progress: progress}}
end
defp render(current, total) do
should_render? && ProgressBar.render(current, total)
end
# use IEx.started?() to render in IEx only
# use Application.get_env(:elixir, :ansi_enabled) to render in both IEx and mix
defp should_render? do
Application.get_env(:elixir, :ansi_enabled)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment