diff --git a/lib/koans/14_agents.ex b/lib/koans/14_agents.ex new file mode 100644 index 0000000..4dddb98 --- /dev/null +++ b/lib/koans/14_agents.ex @@ -0,0 +1,36 @@ +defmodule Agents do + use Koans + + koan "Agents maintain state, so you can ask them about it" do + Agent.start_link(fn() -> "Hi there" end, name: __MODULE__) + assert Agent.get(__MODULE__, &(&1)) == :__ + end + + koan "Update to update the state" do + Agent.start_link(fn() -> "Hi there" end, name: __MODULE__) + + Agent.update(__MODULE__, fn(old) -> + String.upcase(old) + end) + assert Agent.get(__MODULE__, &(&1)) == :__ + end + + koan "Use get_and_update when you need read and change a value in one go" do + Agent.start_link(fn() -> ["Milk"] end, name: __MODULE__) + + old_list = Agent.get_and_update(__MODULE__, fn(old) -> + {old, ["Bread" | old]} + end) + + assert old_list == :__ + assert Agent.get(__MODULE__, &(&1)) == :__ + end + + koan "Somebody has to switch off the light at the end of the day" do + Agent.start_link(fn() -> ["Milk"] end, name: __MODULE__) + + result = Agent.stop(__MODULE__) + + assert result == :__ + end +end diff --git a/lib/runner.ex b/lib/runner.ex index 083ecd5..5912883 100644 --- a/lib/runner.ex +++ b/lib/runner.ex @@ -12,6 +12,7 @@ defmodule Runner do Enums, Processes, Tasks, + Agents, ] def koan?(koan), do: Enum.member?(@modules, koan) diff --git a/test/koans_harness_test.exs b/test/koans_harness_test.exs index 6dc109d..edb5ba9 100644 --- a/test/koans_harness_test.exs +++ b/test/koans_harness_test.exs @@ -222,6 +222,17 @@ defmodule KoansHarnessTest do test_all(Tasks, answers) end + test "Agents" do + answers = [ + "Hi there", + "HI THERE", + {:multiple, [["Milk"], ["Bread", "Milk"]]}, + :ok, + ] + + test_all(Agents, answers) + end + def test_all(module, answers) do module.all_koans |> Enum.zip(answers)