View Source EctoAutoslugField.Slug (ecto_autoslug_field v3.1.0)
This module defines all the required functions and modules to work with.
Examples
To create a simple 'Slug' field do:
defmodule MyCustomSlug do
use EctoAutoslugField.Slug, from: :name_field, to: :slug_field
end
It is also possible to override get_sources/2
and build_slug/2
functions
which are part of the AutoslugField's API.
More complex example with the optional sources and custom slug generation function:
defmodule MyComplexSlug do
use EctoAutoslugField.Slug, to: :slug_field
def get_sources(changeset, _opts) do
basic_fields = [:name, :surname]
if is_company_info_set(changeset) do
# We want to track changes in the person's company:
basic_fields ++ [:company, :position]
else
basic_fields
end
end
def build_slug(sources, changeset) do
super(sources, changeset) # Calls the `SlugGenerator.build_slug/1`
|> String.replace("-", "+")
end
end
It is also possible to always change your slug, even if it was already set:
defmodule ThisSlugShouldChange do
use EctoAutoslugField.Slug, from: :some_field,
to: :slug_field, always_change: true
end
If you want to change slug for only one instance
without setting always_change
option, use force_generate_slug/1
function:
defmodule SimpleSlugForce do
use EctoAutoslugField.Slug, from: :name, to: :some_slug
end
Then you can use SimpleSlugForce.force_generate_slug(changeset)
for any instances, that needs to recreate slugs for some reason.
Be careful with these options, since cool URIs do not change.