Created
July 20, 2018 09:05
-
-
Save eteubert/8d32b404bf0d9b4f4a1482e907619911 to your computer and use it in GitHub Desktop.
Elixir GenServer to render a progress bar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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