Skip to content

Instantly share code, notes, and snippets.

@costaraphael
Created May 10, 2019 01:12
Show Gist options
  • Select an option

  • Save costaraphael/260be02adb6e1f2b8b5831f47b43e214 to your computer and use it in GitHub Desktop.

Select an option

Save costaraphael/260be02adb6e1f2b8b5831f47b43e214 to your computer and use it in GitHub Desktop.

Revisions

  1. costaraphael created this gist May 10, 2019.
    28 changes: 28 additions & 0 deletions nice_pattern.exs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    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"}