Created
March 2, 2017 18:45
-
-
Save AlexVKO/c4879fbf89ebaf7e8a09f925f079db84 to your computer and use it in GitHub Desktop.
elixir recursion example
This file contains 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 BackOfficeApp.Customer do | |
use BackOfficeApp.Web, :model | |
@primary_key {:id, :binary_id, autogenerate: true} | |
schema "customers" do | |
field :title, :string | |
field :first_name, :string | |
field :middle_name, :string | |
field :last_name, :string | |
field :company_name, :string | |
field :is_active, :boolean, default: false | |
field :email, :string | |
field :phone, :string | |
field :mobile, :string | |
field :fax, :string | |
field :website, :string | |
field :notes, :string | |
timestamps() | |
end | |
@doc """ | |
Builds a changeset based on the `struct` and `params`. | |
""" | |
def changeset(struct, params \\ %{}) do | |
struct | |
|> cast(params, [:title, :first_name, :middle_name, :last_name, :company_name, | |
:is_active, :email, :phone, :mobile, :fax, :website, :notes]) | |
|> validate_required([:first_name, :email]) | |
|> capitalize([:title, :first_name, :middle_name, :last_name]) | |
end | |
defp capitalize(changeset, fields) do | |
changeset | |
|> update_many_changes(fields, &(String.capitalize(&1))) | |
end | |
defp update_many_changes(changeset, [h| t], f) do | |
changeset |> update_change(h, f) |> update_many_changes(t, f) | |
end | |
defp update_many_changes(changeset, [], _), do: changeset | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment