Write slugs with the Ash extension

v0.0.3

Mishka Slug 0.0.3 comes with MishkaSlug.Ash, an Ash extension that puts slugify/2 in the change line of an action. change slugify(:title, into: :slug) is the same change as {MishkaSlug.Change, from: :title, into: :slug}, with less to type. This guide adds the extension to a resource, shares options through a preset, saves a taken slug with a suffix and moves an ash_slug resource over.

Before you begin

  • An Ash 3 resource with a title attribute and a slug attribute.
  • Mishka Slug installed. See Get Started. The extension is compiled only when Ash is a dependency of your project.
  • The longer form of the same change, {MishkaSlug.Change, ...}, is in Write the slug in an Ash resource. The options are the same.

Add the extension

List MishkaSlug.Ash in the extensions of the resource. It adds no section to the resource. It only makes slugify/2 available inside change. The data layer is your own, so the example leaves it out.

elixir
defmodule MyApp.Blog.Post do
  use Ash.Resource, domain: MyApp.Blog, extensions: [MishkaSlug.Ash]

  attributes do
    uuid_primary_key :id
    attribute :title, :string, allow_nil?: false, public?: true
    attribute :language, :string, default: "fa", public?: true
    attribute :slug, :string, public?: true, constraints: [max_length: 60]
  end

  actions do
    defaults [:read]

    create :create do
      accept [:title, :language]

      change slugify(:title,
               into: :slug,
               language: :language,
               locales: {MyApp.Sites, :languages, []}
             )
    end
  end
end

The function in locales: returns the site's languages. It gets the changeset first:

elixir
defmodule MyApp.Sites do
  def languages(_changeset), do: ["fa", "en"]
end

Create a record

Create a record without a slug. The change makes it from the title, in the language of the record.

elixir
post = Ash.create!(MyApp.Blog.Post, %{title: "آموزش React در ۱۰ دقیقه"}, action: :create)
post.slug
#=> "آموزش-react-در-۱۰-دقیقه"

post = Ash.create!(MyApp.Blog.Post, %{title: "Hello World: Getting Started!", language: "en"}, action: :create)
post.slug
#=> "hello-world-getting-started"

A title that gives no slug is a changeset error on :title, as with the longer form. See Handle errors and translate messages.

Pass the same options as the change

The first argument of slugify/2 is the attribute or argument the slug is made from. Everything after it is an option of MishkaSlug.Change, and through it every option of MishkaSlug.slugify/2: into:, language:, locales:, skip_if_present?:, separator:, unique_suffix:, preset: and the rest.

MishkaSlug.Ash.Changes.slugify/2 only builds the tuple of the longer form, with :from first:

elixir
MishkaSlug.Ash.Changes.slugify(:title, into: :slug, language: :language)
#=> {MishkaSlug.Change, [from: :title, into: :slug, language: :language]}

So an action that uses either form holds a MishkaSlug.Change with the same options, and one resource can mix both. Code that reads the changes of an action, and MishkaSlug.Change.slug_options/2, see no difference.

elixir
[%{change: {MishkaSlug.Change, options}}] =
  Ash.Resource.Info.action(MyApp.Blog.Post, :create).changes

options
#=> [from: :title, into: :slug, language: :language, locales: {MyApp.Sites, :languages, []}]

Share options with a preset

When many resources make the same kind of slug, keep the options in one place. A preset is a name in the application config, or a {module, function, args} that returns the options.

elixir
# config/config.exs
config :mishka_slug,
  presets: [
    public: [into: :slug, language: :language, locales: {MyApp.Sites, :languages, []}]
  ]
elixir
change slugify(:title, preset: :public)
change slugify(:title, preset: :public, keep: ["."])
change slugify(:title, preset: {MyApp.Slugs, :options, []})

The options next to preset: win over the preset's. The function of a {module, function, args} preset returns a keyword list:

elixir
defmodule MyApp.Slugs do
  def options, do: [into: :slug, locales: ["en"], keep: []]
end

An unknown name, or a preset that is not a keyword list, is an error when the resource compiles, and the message names the preset:

elixir
MishkaSlug.Change.init(from: :title, preset: :missing)
#=> {:error, "invalid options: preset: no preset :missing in config :mishka_slug, :presets"}

The tuple form takes it too: change {MishkaSlug.Change, preset: :public, from: :title}. See Configuration for the setting.

Save a taken slug with a suffix

The change does not check that a slug is free. Add a unique identity on the slug, and set unique_suffix: true to save a slug that the identity refuses as slug-2, then slug-3, and so on.

elixir
identities do
  identity :unique_slug, [:slug]
end

actions do
  create :create do
    accept [:name]
    change slugify(:name, into: :slug, unique_suffix: true)
  end

  update :update do
    accept [:name]
    require_atomic? false
    change slugify(:name, into: :slug, unique_suffix: true)
  end
end
elixir
Ash.create!(MyApp.Blog.Tag, %{name: "Hello World"}, action: :create).slug
#=> "hello-world"

Ash.create!(MyApp.Blog.Tag, %{name: "Hello World"}, action: :create).slug
#=> "hello-world-2"

Ash.create!(MyApp.Blog.Tag, %{name: "Hello World"}, action: :create).slug
#=> "hello-world-3"

How it works:

  • The action saves as usual. The change runs no query of its own, before or after. Only a save that a unique identity of the resource refused for the slug is tried again with the next suffix. Each try is one more write.
  • max_suffix: (default 10) is the highest suffix. When every suffix is taken, the error of the first save is returned.
  • The suffix is joined with the separator:, so "_" gives hello_world_2.
  • A slug that needs a suffix is cut by whole words so the suffix fits max_length.
  • A slug that the action sets itself with skip_if_present?: true is never suffixed.

The change reacts to the error of a unique index (AshPostgres) or of an identity check made before the write (pre_check?: true on the identity, for a data layer without unique indexes such as ETS).

Know the limits of the suffix

The retry runs through Ash.Changeset.around_transaction/2, so:

  • It works for Ash.create/2, Ash.update/2 and the code interfaces that call them.
  • An update action that uses it needs require_atomic? false. Ash refuses the action with Ash.Error.Framework.MustBeAtomic otherwise.
  • It does nothing in Ash.bulk_create/4 and Ash.bulk_update/4. A taken slug there is the usual error.
  • Inside a transaction that someone else opened, such as an action called from another action, Postgres aborts that transaction on the first unique error, so the retry fails with it. Run the action in its own transaction to get the suffix.

Move an ash_slug resource over

The change line of an ash_slug resource works as it is. Swap the extension and keep the actions.

elixir
# before: use Ash.Resource, extensions: [AshSlug]
use Ash.Resource, extensions: [MishkaSlug.Ash]

change slugify(:title, into: :slug, separator: "_", truncate: 30, lowercase?: false)
elixir
Ash.create!(MyApp.Blog.Post, %{title: "Hello, World!"}, action: :create_ash_slug).slug
#=> "Hello_World"

The names that carry over are into, separator, truncate, lowercase? and skip_if_present?. Four things differ:

  • separator: takes only the URL-safe -, ., _ and ~, alone or repeated.
  • ignore is not taken. keep: does that job for ., _ and ~.
  • The slug keeps the script of the title: سلام دنیا with separator: "_" gives سلام_دنیا.
  • A title that gives no slug is a changeset error. The slug is never saved empty.

truncate: is the same option as max_length:, with the same cut by whole words. Give one of the two. Both together are an invalid option.

Next steps