Code Monkey home page Code Monkey logo

grails-slug-generator's Introduction

Grails-slug-generator

Build Status Coverage Status

This plugin generates unique slugs for String properties. Its main use case is to generate unique and nice names for domain instances that can be used in URLs, such as /user/show/<slug>.

For example, instead of having a URL like http://www.domain.com/user/25 with a number identifying the user, you can generate a unique URL based on the user's name: http://www.domain.com/user/ivan-lopez (from name Iván López).

Usage

The plugin provides a Grails Service, slugGeneratorService, that can be injected into any artefact of your Grails application. The service has only one method, generateSlug(Class domainClass, String property, String value), which is used to generate the unique slugs.

How does it work? The method first generates a slug from the given value and then checks whether that slug is already used by another domain instance of the given type. If the slug is unique, then the method returns that value. Otherwise, it appends a number and tries again. This is repeated until a unique slug is found and returned.

The typical use case is to automatically set the slug when inserting a new domain object or when updating an existing one whose source property (for example 'name') has changed. Here's a concrete example:

class Dummy {
    def slugGeneratorService

    String name
    String slug = ""

    def beforeInsert() {
        this.slug = slugGeneratorService.generateSlug(this.class, "slug", name)
    }

    def beforeUpdate() {
        if (isDirty('name')) {
            this.slug = slugGeneratorService.generateSlug(this.class, "slug", name)
        }
    }
}

With the above code, you get the following behavior when using the Dummy domain class:

def dummy = new Dummy(name:"Iván López").save()
assert dummy.slug == "ivan-lopez"

dummy.name = "Another name!!"
dummy.save(flush:true)
def dummyUpdated = Dummy.get(1)
assert dummyUpdated.slug == "another-name"

def dummy2 = new Dummy(name:"Iván López").save()
assert dummy2.slug == "ivan-lopez-1"

The plugin supports full UTF-8, so you can use, for instance, ciryllic chars or right-to-left writing. Check out the tests for more examples.

But, if you need only ascii slugs, you can activate a strict mode that filters all non ascii characters.

class Dummy {
    // [...]
    def beforeInsert() {
        this.slug = slugGeneratorService.generateSlug(this.class, "slug", name, true)
    }

    def beforeUpdate() {
        if (isDirty('name')) {
            this.slug = slugGeneratorService.generateSlug(this.class, "slug", name, true)
        }
    }
}

Additional codec

The plugin also includes a SlugCodec that you can call like the other Grails builtin codecs:

assert "ivan-lopez" == "Iván López!!".encodeAsSlug()

Version info

  • 0.5 - 01/Aug/2014 - Add a check for null strings. Thanks again to Piotr Athlan Pelczar.
  • 0.4 - 22/Jun/2014 - Fixed issue with some polish characters. Thanks to Piotr Athlan Pelczar.
  • 0.3.1 - 06/Apr/2013 - Removed unnecessary maven repositories.
  • 0.3 - 06/Apr/2013 - Fixed issue #4 and added additional param to generate ascii-only slugs. Thanks @niwibe for the pull-requests.
  • 0.2 - 11/Jan/2013 - Fixed issue with some characters like '¿' and '¡'
  • 0.1 - 02/Aug/2012 - Initial version.

grails-slug-generator's People

Contributors

athlan avatar ilopmar avatar pledbrook avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

grails-slug-generator's Issues

Problems with '¿' character

Hi,

Leaving a part that this plugin is amazing, I have found that the char '¿' is not removed when using the slugGeneratorService.

Could it be a bug?

Thanks in advance!

Wrong slug

Hello,

I have noticed that the following text "æ³o & h³æ" gives the next slug: "æ³o-h³æ" which I think is wrong.

Should not be "ae-h-ae"?

One more time, great job, this plug-in is really useful.

Problem with Polish Ł and ł characters

There is the problem with Polish Ł and ł characters.

Please try:

"Pchnąć w tę łódź jeża lub ośm skrzyń fig"

result:

"pchnac-w-te-łodz-jeza-lub-osm-skrzyn-fig"

expected:

"pchnac-w-te-lodz-jeza-lub-osm-skrzyn-fig"

Improvement proposal

First of all, let me tell you that I've been using this plugin for a long time now and it's great, I use it as an example of a perfectly simple and useful plugin 😄

I'm currently developing a plugin that uses slug-generator internally and found some kind of an issue. I can resolve from my code but wanted to let you know my opinion.

This assertion fails:

assert "CONCHETA D´AGOSTINO".encodeAsSlug() == 'concheta-dagostino'

The plugin generates the following slug: concheta-d´agostino and the character ´ is not acceptable for me.

Looking at your code, I found the asciiOnly option resolves my issue and that's what I'm going to use. So my new code is:

assert SlugCodec.encode("CONCHETA D´AGOSTINO", true) == 'concheta-dagostino'

But my question is, shouldn't it be the default behaviour?

Does this plugin works in grails 3.1.x?

Thanks for the plugin. I have been using this happily since grails 2.5.1. Recently I am starting a new project and it seems the domain object cannot have the slugGeneratorService injected. Am I missing anything or the plugin isn't working in grails 3.1.x?

(User Error) Unable to resolve using Grails 2.3

First, great plugin, thanks!

I'm updating to grails 2.3 and I am getting the following error:

Bad artifact coordinates :slug-generator:0.3.1,, expected format is <groupId>:<artifactId>[:<extension>[:<classifier>]]:<version>

In 2.2 the following worked, but it does not work in 2.3

compile "org.grails.plugins:slug-generator:0.3.1"

Any suggestions on how get this to resolve in 2.3?

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.