Skip to content

Instantly share code, notes, and snippets.

@rpip
Last active August 29, 2015 14:00
Show Gist options
  • Save rpip/4a154140df38be45d118 to your computer and use it in GitHub Desktop.
Save rpip/4a154140df38be45d118 to your computer and use it in GitHub Desktop.
defmodule DefStructPlusPlus do
@doc """
Macro for defining structs
## Examples
defmodule Models do
import DefStructPlusPlus
defstruct Blob, content: nil, created: nil
end
"""
defmacro defstruct(name, attrs, code_block \\ nil ) do
quote do
defmodule unquote(name) do
defstruct unquote(attrs)
# unquote code block
unquote(code_block)
end
end
end
end
defmodule Models do
import DefStructPlusPlus
defstruct Blob, id: nil, content: nil, created: nil do
defimpl String.Chars do
def to_string(blob) do
"Blob ##{blob.id} <#{blob.created}>"
end
end
end
defstruct User, username: nil, email: nil, password: nil do
defimpl String.Chars do
def to_string(user) do
"username: #{user.username}, email: #{user.email}"
end
end
end
end
defmodule Test do
require Models
alias Models.User, as: User
def dummy_user() do
%User{:username => "Mawuli", :email => "[email protected]"}
|> to_string
end
end
# to run, start iex
# c "defstructplusplus.ex"
# Test.dummy_user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment