Created
May 25, 2016 12:21
-
-
Save nwalker/cdcdc700cb34fdf928b6be3851f6c875 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 StructDefaults do | |
defmacro __using__(opts) do | |
name = case opts[:name] do | |
nil -> __CALLER__.module |> Module.split() |> List.last() | |
b when is_binary(b) -> b | |
end | |
mod = __CALLER__.module | |
quote location: :keep do | |
require StructDefaults | |
defdelegate([ | |
fetch(t, k), | |
get_and_update(t, k, l) | |
], to: Map) | |
defimpl String.Chars, for: unquote(mod) do | |
def to_string(u) do | |
#TODO: replace with something smarter | |
inspect(u) | |
end | |
end | |
defimpl Inspect, for: unquote(mod) do | |
import Inspect.Algebra | |
def inspect(user, opts) do | |
concat ["#", unquote(name), "<", to_doc(Map.from_struct(user) |> Enum.to_list(), opts), ">"] | |
end | |
end | |
end | |
end | |
end |
This file contains hidden or 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 SomeStruct | |
defstruct [:a, :b, :c] | |
use StructDefaults, name: "SomeOtherNameForSomeStruct" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment