Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Given that we have a `User` module, that looks something like this:
defmodule User do
defstruct [:name]
def changeset(user, params) do
# ...
end
end
# When writing code like this, with the struct literal syntax `%Usert{}`, we create an `export` dependency on `User`:
defmodule Accounts do
def create_user(params) do
%User{}
|> User.changeset(params)
|> Repo.insert()
end
def update_user(%User{} = user, params) do
user
|> User.changeset(params)
|> Repo.update()
end
def update_user(_, _) do
raise "INVALID"
end
end
# But when writing it like this, we only have a `runtime` dependency, while still basically doing the same thing:
defmodule Accounts do
def create_user(params) do
User
|> struct!(%{})
|> User.changeset(params)
|> Repo.insert()
end
def update_user(%{__struct__: User} = user, params) do
user
|> User.changeset(params)
|> Repo.update()
end
def update_user(_, _) do
raise "INVALID"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment