@@ -57,12 +57,37 @@ defmodule Ecto.ChangesetTest do
5757 def dump ( _ ) , do: :error
5858 end
5959
60+ defmodule Email do
61+ use Ecto.Type
62+
63+ def type , do: :string
64+ def cast ( val ) when is_binary ( val ) , do: { :ok , val }
65+ def cast ( _ ) , do: :error
66+ def load ( val ) when is_binary ( val ) , do: { :ok , val }
67+ def load ( _ ) , do: :error
68+ def dump ( val ) when is_binary ( val ) , do: { :ok , val }
69+ def dump ( _ ) , do: :error
70+
71+ def equal? ( email_a , email_b ) when is_binary ( email_a ) and is_binary ( email_b ) do
72+ [ username_a , domain_a ] = String . split ( email_a , "@" )
73+ [ username_b , domain_b ] = String . split ( email_b , "@" )
74+
75+ [ significant_a | _ ] = String . split ( username_a , "+" )
76+ [ significant_b | _ ] = String . split ( username_b , "+" )
77+
78+ significant_a == significant_b && domain_a == domain_b
79+ end
80+
81+ def equal? ( a , b ) , do: a == b
82+ end
83+
6084 defmodule Post do
6185 use Ecto.Schema
6286
6387 schema "posts" do
6488 field :token , :integer , primary_key: true
6589 field :title , :string , default: ""
90+ field :author_email , Email
6691 field :slug , CustomSlug
6792 field :body
6893 field :uuid , :binary_id
@@ -95,7 +120,7 @@ defmodule Ecto.ChangesetTest do
95120 end
96121
97122 defp changeset ( schema \\ % Post { } , params ) do
98- cast ( schema , params , ~w( id token title slug body upvotes decimal color topics tags virtual) a )
123+ cast ( schema , params , ~w( id token title author_email slug body upvotes decimal color topics tags virtual) a )
99124 end
100125
101126 defmodule CustomError do
@@ -1055,6 +1080,15 @@ defmodule Ecto.ChangesetTest do
10551080 assert changeset . valid?
10561081 assert changeset . errors == [ ]
10571082 assert validations ( changeset ) == [ slug: { :inclusion , ~w( foo) } ]
1083+
1084+ # type with custom equal function
1085+ changeset =
1086+ changeset ( % { "author_email" => "[email protected] " } ) 1087+ |> validate_inclusion ( :author_email , [ "[email protected] " ] ) 1088+
1089+ assert changeset . valid?
1090+ assert changeset . errors == [ ]
1091+ assert validations ( changeset ) == [ author_email: { :inclusion , [ "[email protected] " ] } ] 10581092 end
10591093
10601094 test "validate_subset/3" do
0 commit comments