Skip to content

Instantly share code, notes, and snippets.

@costaraphael
Created May 10, 2019 01:12
Show Gist options
  • Save costaraphael/260be02adb6e1f2b8b5831f47b43e214 to your computer and use it in GitHub Desktop.
Save costaraphael/260be02adb6e1f2b8b5831f47b43e214 to your computer and use it in GitHub Desktop.
Builder pattern in Elixir (don't do this!!!)
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