Last active
February 23, 2016 10:02
-
-
Save seaneshbaugh/2b47aaa59a07c9c22f59 to your computer and use it in GitHub Desktop.
user.ex
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 MyApp.User do | |
| use MyApp.Web, :model | |
| schema "users" do | |
| field :username, :string | |
| field :email, :string | |
| field :password, :string, virtual: true | |
| field :password_confirmation, :string, virtual: true | |
| field :encrypted_password, :string | |
| timestamps | |
| end | |
| def changeset(model, action, params \\ nil) do | |
| model | |
| |> cast(params, required_fields_for(action), optional_fields_for(action)) | |
| |> validate_password_confirmation | |
| |> set_hashed_password | |
| end | |
| defp required_fields_for(:create) do | |
| ~w(username email password password_confirmation) | |
| end | |
| defp required_fields_for(:update) do | |
| ~w(username email) | |
| end | |
| defp optional_fields_for(:create) do | |
| ~w() | |
| end | |
| defp optional_fields_for(:update) do | |
| ~w(password password_confirmation) | |
| end | |
| defp validate_password_confirmation(changeset) do | |
| password = Ecto.Changeset.get_field(changeset, :password, "") | |
| password_confirmation = Ecto.Changeset.get_field(changeset, :password_confirmation, "") | |
| case password do | |
| ^password_confirmation -> changeset | |
| _ -> Ecto.Changeset.add_error(changeset, :password, "must match confirmation") | |
| end | |
| end | |
| # Ignore for now that this isn't actually hashing anything. | |
| defp hash_password(password) do | |
| password <> "ABCDEFG" | |
| end | |
| defp set_hashed_password(changeset) do | |
| password = Ecto.Changeset.get_field(changeset, :password) | |
| case password do | |
| nil -> changeset | |
| pwd -> Ecto.Changeset.put_change(changeset, :encrypted_password, hash_password(pwd)) | |
| end | |
| end | |
| end |
Yeah, I'm digging these functions for required and optional fields!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting way of handling required and optional fields! 😄