Code Monkey home page Code Monkey logo

ecto_autoslug_field's Introduction

EctoAutoslugField

Build Status Coverage Status Module Version Hex Docs License

ecto_autoslug_field is a reusable Ecto library which can automatically create slugs from other fields. We use slugify as a default slug-engine.

We only depend on the ecto package (we do not deal with ecto_sql at all). We support ecto >= 3.7 and ecto < 4!

See this blog post for more information.

Installation

def deps do
  [
    {:ecto_autoslug_field, "~> 3.1"}
  ]
end

Options

There are several options to configure.

Required:

  • :to - represents the slug field name where to save value to

Optional:

  • :from - represents the source fields from which to build slug, if this option is not set you have to override get_sources/2 function
  • :always_change - if this option is set slug will be recreated from the given sources each time maybe_generate_slug function is called

Functions

  • get_sources/2 - this function is used to get sources for the slug, docs.
  • build_slug/2 - this function is a place to modify the result slug, docs.

Examples

The simplest example:

defmodule EctoSlugs.Blog.Article.TitleSlug do
  use EctoAutoslugField.Slug, from: :title, to: :slug
end

defmodule EctoSlugs.Blog.Article do
  use Ecto.Schema
  import Ecto.Changeset
  alias EctoSlugs.Blog.Article
  alias EctoSlugs.Blog.Article.TitleSlug

  schema "blog_articles" do
    field :breaking, :boolean, default: false
    field :content, :string
    field :title, :string

    field :slug, TitleSlug.Type

    timestamps()
  end

  def changeset(model, params \\ :invalid) do
    model
    |> cast(params, [:title, :content, :breaking])
    |> validate_required([:title, :content])
    |> unique_constraint(:title)
    |> TitleSlug.maybe_generate_slug()
    |> TitleSlug.unique_constraint()
  end
end

See this tutorial for some more examples.

Changelog

See CHANGELOG.md.

Copyright and License

Copyright (c) 2016 Nikita Sobolev

This library is released under the MIT License. See the LICENSE.md file for further details.

ecto_autoslug_field's People

Contributors

chrisalley avatar dependabot-preview[bot] avatar dependabot[bot] avatar indocomsoft avatar kianmeng avatar nlap avatar nurges avatar ranyefet avatar seantanly avatar sobolevn avatar suhrawardi avatar txssu avatar xtian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ecto_autoslug_field's Issues

`Ecto.Field`: dig out `autogenerate` option

Maybe it is possible to use this option effectively?

Tasks:

  • is there any way to access schema's data from types's autogenerate/0?
  • is possible to call functions such as get_sources/2 from autogenerate/0?
  • is it even reasonable?

Ecto@3 support

We need to release a new version with ecto@3 support.

Help is wanted, since I don't have much time to work on this issue.

Slugger v0.2.0 released

Hi,
maybe you could use the new function

Slugger.truncate_slug(slug, max_length, options \\ [])

which is part of slugger v0.2.0. ๐Ÿ’ƒ

Function build_slug/1 has no local return

Here's the error:

lib/ecto_autoslug_field/slug.ex:3:no_return
Function build_slug/1 has no local return.
________________________________________________________________________________
lib/ecto_autoslug_field/slug.ex:3:no_return
Function build_slug/2 has no local return.
________________________________________________________________________________
lib/ecto_autoslug_field/slug.ex:218:call
The function call will not succeed.

EctoAutoslugField.SlugBase.build_slug(_ :: any(), nil)

will never return since the 2nd arguments differ
from the success typing arguments:

(Keyword.t(), %Ecto.Changeset{
  :action => atom(),
  :changes => %{atom() => _},
  :constraints => [
    %{
      :constraint => binary(),
      :error_message => binary(),
      :error_type => atom(),
      :field => atom(),
      :match => :exact | :prefix | :suffix,
      :type => :check | :exclusion | :foreign_key | :unique
    }
  ],
  :data => nil | map(),
  :empty_values => _,
  :errors => Keyword.t({_, _}),
  :filters => %{atom() => _},
  :params => nil | %{binary() => _},
  :prepare => [(_ -> any())],
  :repo => atom(),
  :repo_opts => Keyword.t(),
  :required => [atom()],
  :types =>
    nil
    | %{
        atom() =>
          atom()
          | {:array | :assoc | :embed | :in | :map | :maybe | :param, _}
          | {:parameterized, atom(), _}
      },
  :valid? => boolean(),
  :validations => Keyword.t()
})

I'm using the library according to the docs.

Two or most posts with same title

I wanted to ask that in implementing the unique constraint for lets say a post title to be converted to a slug, is it possible that if a title already exists with the same words/characters then while creating a new post, it adds random characters or numbers at the end to differentiate the post slugs.

In rails the FriendlyId gem takes care of this. As an example I am posting images from a rails app using FriendlyId to create slugs from the post's title.

slug-post

Second post created with the same title:

slug-post-unique-second

Any help on this will be appreciated.

Forcing regenerating the slug on a particular record

Hello,

Let's say I want to force the regeneration of a slug on a particular record without having to set globally the always_change option, what's the short way of doing that?
What do you think of having a function called force_generate_slug?

Thanks.

Dialyzer errors

Hi,

slug.ex is causing Dialyzer errors for me:

lib/ecto_autoslug_field/slug.ex:2: Function get_sources/2 has no local return
lib/ecto_autoslug_field/slug.ex:168: The pattern 'nil' can never match the type 'name'

Thanks!

README typo

Hey, just noticed: you have CHANGELOG link broken in your README.

PS: thanks for your work)

Help with getting it to insert?

Hi,

I've been attempting to apply the tutorials to the following project: https://github.com/blcksheep80/blcksheepio-api

However, I can't seem to get the slug to generate? I created a field: https://github.com/blcksheep80/blcksheepio-api/blob/master/lib/blcksheepio_api/classification/fields/name_slug.ex

Which I've attempted to apply to https://github.com/blcksheep80/blcksheepio-api/blob/master/lib/blcksheepio_api/classification/category.ex

However, whenever I attempt to insert a new category I get the following back:

22:25:56.678 [info] == Migrated 20190708054130 in 0.0s
[debug] QUERY ERROR db=1.0ms queue=1.4ms
INSERT INTO categories (name,inserted_at,updated_at,id) VALUES (?,?,?,?) ["delectus ab a qui eius", ~N[2019-10-16 19:25:57], ~N[2019-10-16 19:25:57], <<106, 124, 218, 218, 100, 235, 78, 227, 169, 137, 129, 200, 81, 162, 135, 94>>]
** (Mariaex.Error) (1364): Field 'slug' doesn't have a default value
(ecto_sql) lib/ecto/adapters/mysql.ex:232: Ecto.Adapters.MySQL.insert/6
(ecto) lib/ecto/repo/schema.ex:649: Ecto.Repo.Schema.apply/4
(ecto) lib/ecto/repo/schema.ex:262: anonymous fn/15 in Ecto.Repo.Schema.do_insert/4
(ecto) lib/ecto/repo/schema.ex:164: Ecto.Repo.Schema.insert!/4
(elixir) lib/stream.ex:1341: Stream.do_repeatedly/3
(elixir) lib/enum.ex:2486: Enum.take/2
(blcksheepio_api) lib/mix/tasks/seed.ex:17: Mix.Tasks.BlcksheepIoApi.Seed.seed/1
(mix) lib/mix/task.ex:331: Mix.Task.run_task/3
(mix) lib/mix/task.ex:365: Mix.Task.run_alias/3
(mix) lib/mix/task.ex:292: Mix.Task.run/2
(mix) lib/mix/task.ex:365: Mix.Task.run_alias/3
(mix) lib/mix/task.ex:292: Mix.Task.run/2
(mix) lib/mix/cli.ex:79: Mix.CLI.run_task/2
(elixir) lib/code.ex:767: Code.require_file/2

Auto increment suffix of same slugs

Hello,

Thanks for the great lib
In my use case the same slug can be generated. When that happens the unique constraint kicks in and fails the changeset.

I would like instead to try to insert the same entity with a auto incremented number

For example:

changeset = Todo.changeset(Todo, %{text: "My Todo"})
todo = Repo.insert!(changeset)

Should return:

%Todo{text: "My Todo", slug: "my-todo"}

If I run the same insert again, I want to get back:

%Todo{text: "My Todo", slug: "my-todo-2"}

Any tips on how to achieve that?
Is this feature planned for this library?

Thanks,
Ran.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.