Adds a koan to demonstrate the use of deriving a default behaviour
This commit is contained in:
@@ -5,14 +5,25 @@ defmodule Protocols do
|
||||
|
||||
defprotocol School, do: def enrol(person)
|
||||
|
||||
defmodule Student, do: defstruct name: ""
|
||||
defmodule Baker, do: defstruct name: ""
|
||||
defmodule Dancer do
|
||||
defstruct name: "", dance_style: ""
|
||||
defimpl School, for: Any do
|
||||
def enrol(person) do
|
||||
"#{person.name} enrolled at school"
|
||||
end
|
||||
end
|
||||
|
||||
defimpl School, for: Student do
|
||||
def enrol(student), do: "#{student.name} enrolled at secondary school"
|
||||
defmodule Student do
|
||||
@derive School
|
||||
defstruct name: ""
|
||||
end
|
||||
|
||||
defmodule Musician, do: defstruct name: "", instrument: ""
|
||||
defmodule Dancer, do: defstruct name: "", dance_style: ""
|
||||
defmodule Baker, do: defstruct name: ""
|
||||
|
||||
defimpl School, for: Musician do
|
||||
def enrol(musician) do
|
||||
"#{musician.name} signed up for #{musician.instrument}"
|
||||
end
|
||||
end
|
||||
|
||||
defimpl School, for: Dancer do
|
||||
@@ -20,13 +31,18 @@ defmodule Protocols do
|
||||
end
|
||||
|
||||
koan "Sharing an interface is the secret at school" do
|
||||
student = %Student{name: "Emily"}
|
||||
musician = %Musician{name: "Andre", instrument: "violin"}
|
||||
dancer = %Dancer{name: "Darcy", dance_style: "ballet"}
|
||||
|
||||
assert School.enrol(student) == ___
|
||||
assert School.enrol(musician) == ___
|
||||
assert School.enrol(dancer) == ___
|
||||
end
|
||||
|
||||
koan "Sometimes we all use the same" do
|
||||
student = %Student{name: "Emily"}
|
||||
assert School.enrol(student) == ___
|
||||
end
|
||||
|
||||
koan "If you don't comply you can't get in" do
|
||||
assert_raise ___, fn ->
|
||||
School.enrol(%Baker{name: "Delia"})
|
||||
|
@@ -4,7 +4,8 @@ defmodule ProtocolsTests do
|
||||
|
||||
test "Protocols" do
|
||||
answers = [
|
||||
{:multiple, ["Emily enrolled at secondary school", "Darcy enrolled for ballet"]},
|
||||
{:multiple, ["Andre signed up for violin", "Darcy enrolled for ballet"]},
|
||||
"Emily enrolled at school",
|
||||
Protocol.UndefinedError
|
||||
]
|
||||
|
||||
|
Reference in New Issue
Block a user