Skip to content

Instantly share code, notes, and snippets.

@gvaughn
Forked from costaraphael/nice_pattern.exs
Created July 14, 2020 04:27
Show Gist options
  • Save gvaughn/6747d8aa01645f41163ac5297d1ac1db to your computer and use it in GitHub Desktop.
Save gvaughn/6747d8aa01645f41163ac5297d1ac1db 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