Change protocol examples
This commit is contained in:
@@ -3,49 +3,49 @@ defmodule Protocols do
|
|||||||
|
|
||||||
@intro "Want to follow the rules? Adhere to the protocol!"
|
@intro "Want to follow the rules? Adhere to the protocol!"
|
||||||
|
|
||||||
defprotocol(School, do: def(enroll(person)))
|
defprotocol(Artist, do: def(perform(artist)))
|
||||||
|
|
||||||
defimpl School, for: Any do
|
defimpl Artist, for: Any do
|
||||||
def enroll(_) do
|
def perform(_) do
|
||||||
"Pupil enrolled at school"
|
"Artist showed performance"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
defmodule Student do
|
defmodule Painter do
|
||||||
@derive School
|
@derive Artist
|
||||||
defstruct name: ""
|
defstruct name: ""
|
||||||
end
|
end
|
||||||
|
|
||||||
defmodule(Musician, do: defstruct(name: "", instrument: ""))
|
defmodule(Musician, do: defstruct(name: "", instrument: ""))
|
||||||
defmodule(Dancer, do: defstruct(name: "", dance_style: ""))
|
defmodule(Dancer, do: defstruct(name: "", dance_style: ""))
|
||||||
defmodule(Baker, do: defstruct(name: ""))
|
defmodule(Physicist, do: defstruct(name: ""))
|
||||||
|
|
||||||
defimpl School, for: Musician do
|
defimpl Artist, for: Musician do
|
||||||
def enroll(musician) do
|
def perform(musician) do
|
||||||
"#{musician.name} signed up for #{musician.instrument}"
|
"#{musician.name} played #{musician.instrument}"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
defimpl School, for: Dancer do
|
defimpl Artist, for: Dancer do
|
||||||
def enroll(dancer), do: "#{dancer.name} enrolled for #{dancer.dance_style}"
|
def perform(dancer), do: "#{dancer.name} performed #{dancer.dance_style}"
|
||||||
end
|
end
|
||||||
|
|
||||||
koan "Sharing an interface is the secret at school" do
|
koan "Sharing an interface is the secret at school" do
|
||||||
musician = %Musician{name: "Andre", instrument: "violin"}
|
musician = %Musician{name: "Andre", instrument: "violin"}
|
||||||
dancer = %Dancer{name: "Darcy", dance_style: "ballet"}
|
dancer = %Dancer{name: "Darcy", dance_style: "ballet"}
|
||||||
|
|
||||||
assert School.enroll(musician) == ___
|
assert Artist.perform(musician) == ___
|
||||||
assert School.enroll(dancer) == ___
|
assert Artist.perform(dancer) == ___
|
||||||
end
|
end
|
||||||
|
|
||||||
koan "Sometimes we all use the same" do
|
koan "Sometimes we all use the same" do
|
||||||
student = %Student{name: "Emily"}
|
painter = %Painter{name: "Emily"}
|
||||||
assert School.enroll(student) == ___
|
assert Artist.perform(painter) == ___
|
||||||
end
|
end
|
||||||
|
|
||||||
koan "If you don't comply you can't get in" do
|
koan "If you are not an artist, you can't show performance" do
|
||||||
assert_raise ___, fn ->
|
assert_raise ___, fn ->
|
||||||
School.enroll(%Baker{name: "Delia"})
|
Artist.perform(%Physicist{name: "Delia"})
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user