-
-
Save gvaughn/6747d8aa01645f41163ac5297d1ac1db to your computer and use it in GitHub Desktop.
Builder pattern in Elixir (don't do this!!!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Person do | |
defstruct [:name, :age] | |
def with do | |
{Person.Builder, %{}} | |
end | |
defmodule Builder do | |
def unquote(:'$handle_undefined_function')(:and_with, [{__MODULE__, _acc} = tuple]) do | |
tuple | |
end | |
def unquote(:'$handle_undefined_function')(attr, [value, {__MODULE__, acc}]) do | |
{__MODULE__, Map.put(acc, attr, value)} | |
end | |
def build!({__MODULE__, attrs}) do | |
struct!(Person, attrs) | |
end | |
end | |
end | |
person = Person | |
.with.name("John") | |
.and_with.age(35) | |
.build!() | |
IO.inspect(person) #=> %Person{age: 35, name: "John"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment