Created
March 9, 2019 00:07
-
-
Save aharpole/5af4e613b68e86be97f8d19a10dc20fb to your computer and use it in GitHub Desktop.
refactored simple genserver
This file contains hidden or 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 IncrementableValue do | |
use GenServer | |
defstruct [:value, :increment_by] | |
@type t :: %__MODULE__{ | |
value: integer, | |
increment_by: integer | |
} | |
def start_link(opts) do | |
{state_opts, opts} = Keyword.split(opts, [:increment_by]) | |
state_opts = Keyword.merge([increment_by: 1], state_opts) #default to incrementing by 1 still | |
GenServer.start_link(__MODULE__, state_opts, opts) | |
end | |
def init(%{increment_by: increment_by}) do | |
{:ok, %__MODULE__{value: 1, increment_by: increment_by}} | |
end | |
def handle_call(:get_data, _, %{value: value} = state) do | |
{:reply, value, state} | |
end | |
def handle_cast(:increment, state) do | |
new_state = Map.put(state, :value, &(&1 + state.increment_by)) | |
{:noreply, state} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment