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)
|
defprotocol School, do: def enrol(person)
|
||||||
|
|
||||||
defmodule Student, do: defstruct name: ""
|
defimpl School, for: Any do
|
||||||
defmodule Baker, do: defstruct name: ""
|
def enrol(person) do
|
||||||
defmodule Dancer do
|
"#{person.name} enrolled at school"
|
||||||
defstruct name: "", dance_style: ""
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
defimpl School, for: Student do
|
defmodule Student do
|
||||||
def enrol(student), do: "#{student.name} enrolled at secondary school"
|
@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
|
end
|
||||||
|
|
||||||
defimpl School, for: Dancer do
|
defimpl School, for: Dancer do
|
||||||
@@ -20,13 +31,18 @@ defmodule Protocols do
|
|||||||
end
|
end
|
||||||
|
|
||||||
koan "Sharing an interface is the secret at school" do
|
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"}
|
dancer = %Dancer{name: "Darcy", dance_style: "ballet"}
|
||||||
|
|
||||||
assert School.enrol(student) == ___
|
assert School.enrol(musician) == ___
|
||||||
assert School.enrol(dancer) == ___
|
assert School.enrol(dancer) == ___
|
||||||
end
|
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
|
koan "If you don't comply you can't get in" do
|
||||||
assert_raise ___, fn ->
|
assert_raise ___, fn ->
|
||||||
School.enrol(%Baker{name: "Delia"})
|
School.enrol(%Baker{name: "Delia"})
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ defmodule ProtocolsTests do
|
|||||||
|
|
||||||
test "Protocols" do
|
test "Protocols" do
|
||||||
answers = [
|
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
|
Protocol.UndefinedError
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user