Skip to content

Instantly share code, notes, and snippets.

@nwalker
Created May 25, 2016 12:21
Show Gist options
  • Save nwalker/cdcdc700cb34fdf928b6be3851f6c875 to your computer and use it in GitHub Desktop.
Save nwalker/cdcdc700cb34fdf928b6be3851f6c875 to your computer and use it in GitHub Desktop.
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
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