When UUID is not enough!
Provides some custom Ecto
types to work with identifier
fields that are generated using:
Full docs available on hexdocs.pm
Nanoid are as safe and sound as UUIDs, but more compact. Check them out in real life! 🌈
The type defines an autogenerate/0
that can generate a nanoid for you at
"insert-time". You don't have to worry about adding the field to your changeset
cast
/validate_required
(just like those auto-generated timestamps)!
defmodule Post do
use Ecto.Schema
alias Ecto.Nanoid
schema "posts" do
field(:number, Ecto.Nanoid, autogenerate: true)
field(:data, :string)
end
end
And voila!
iex> changeset = Post.changeset(%Post{}, %{data: "the answer to everything"})
iex> changeset.changes.number
nil # coz it's autogenerated!
iex> a_tough_one = Repo.insert!(changeset)
iex> %Post{
id: 42,
number: "swv~u7bIyewzBFOKuFbbD", # there we have it!
}
If you pass in a
:number
in theparams
, a nanoid will not be autogenerated for you. For more juicy details seeEcto.Schema
.
Well, to make Ecto compute the ID only at "insert-time", you gotta define an
autogenerate/0
for that field's type
. Which means, this nanoid field needs
to be of a custom Ecto.Type
, ala Ecto.Nanoid
.
Well of course! An example is coming soon!
Coming shortly folks!
The package can be installed by adding ecto_identifier
to your list of
dependencies in mix.exs
:
def deps do
[
{:ecto_identifier, "~> 0.1.0"}
]
end
Copyright 2018 Ananya Bahadur
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.