Protocol examples updated to use Structs

This commit is contained in:
gemcfadyen
2016-05-25 17:44:42 +01:00
parent 65553d966f
commit c970ed01dd
4 changed files with 67 additions and 2 deletions

50
lib/koans/16_protocols.ex Normal file
View File

@@ -0,0 +1,50 @@
defmodule Protocols do
use Koans
defprotocol School do
def enrol(person)
end
defmodule Student do
defstruct name: ""
end
defmodule Dancer do
defstruct name: "", dance_style: ""
end
defmodule Baker do
defstruct name: ""
end
defimpl School, for: Student do
def enrol(student) do
"#{student.name} enrolled at secondary school"
end
end
defimpl School, for: Dancer do
def enrol(dancer) do
"#{dancer.name} enrolled for #{dancer.dance_style}"
end
end
defmodule EveningSchool do end
koan "Sharing an interface is the secret at school" do
student = %Student{name: "Emily"}
assert School.enrol(student) == ___
end
koan "Dancers share but belong to a different school" do
dancer = %Dancer{name: "Darcy", dance_style: "ballet"}
assert School.enrol(dancer) == ___
end
koan "If you don't comply you can't get in" do
assert_raise ___, fn ->
School.enrol(%Baker{name: "Delia"})
end
end
end

View File

@@ -15,6 +15,7 @@ defmodule Runner do
Processes,
Tasks,
Agents,
Protocols,
]
def koan?(koan), do: Enum.member?(@modules, koan)

View File

@@ -1,2 +1,2 @@
%{"exfswatch": {:hex, :exfswatch, "0.1.1"},
"fs": {:hex, :fs, "0.9.2"}}
%{"exfswatch": {:hex, :exfswatch, "0.1.1", "7ccf6fc9b443d04dada3e50b21f910b4d0e4546ce7772dc6d4181fb929ea186f", [:mix], [{:fs, "~> 0.9", [hex: :fs, optional: false]}]},
"fs": {:hex, :fs, "0.9.2", "ed17036c26c3f70ac49781ed9220a50c36775c6ca2cf8182d123b6566e49ec59", [:rebar], []}}

View File

@@ -0,0 +1,14 @@
defmodule ProtocolsTests do
use ExUnit.Case
import TestHarness
test "Protocols" do
answers = [
"Emily enrolled at secondary school",
"Darcy enrolled for ballet",
Protocol.UndefinedError
]
test_all(Protocols, answers)
end
end