Skip to content

Instantly share code, notes, and snippets.

@deluan
Last active September 23, 2015 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deluan/600968 to your computer and use it in GitHub Desktop.
Save deluan/600968 to your computer and use it in GitHub Desktop.
/*
* Copyright 2010 Deluan Cotts (grails@deluan.com.br)
*
* 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.
*/
package com.deluan.grails.codecs
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* Strip all non word chars, convert to lowercase
*/
class PermalinkCodec {
private static final String[] CARACTERES_SEM_ACENTO
private static final Pattern[] PATTERNS
static {
CARACTERES_SEM_ACENTO = ["a", "e", "i", "o", "u", "c", "n"]
PATTERNS = new Pattern[CARACTERES_SEM_ACENTO.length]
PATTERNS[0] = Pattern.compile("[áàãâä]", Pattern.CASE_INSENSITIVE)
PATTERNS[1] = Pattern.compile("[éèêë]", Pattern.CASE_INSENSITIVE)
PATTERNS[2] = Pattern.compile("[íìïî]", Pattern.CASE_INSENSITIVE)
PATTERNS[3] = Pattern.compile("[óòöõô]", Pattern.CASE_INSENSITIVE)
PATTERNS[4] = Pattern.compile("[úùüû]", Pattern.CASE_INSENSITIVE)
PATTERNS[5] = Pattern.compile("ç", Pattern.CASE_INSENSITIVE)
PATTERNS[6] = Pattern.compile("ñ", Pattern.CASE_INSENSITIVE)
}
private static String replaceSpecial(String text) {
String result = text
for (int i = 0; i < PATTERNS.length; i++) {
Matcher matcher = PATTERNS[i].matcher(result)
result = matcher.replaceAll(CARACTERES_SEM_ACENTO[i])
}
return result
}
static encode = {str ->
str = replaceSpecial(str.toString().toLowerCase())
return str.replaceAll("\\W", "-")
}
}
@deluan
Copy link
Author

deluan commented Sep 28, 2010

To use it in your Grails project, save it in

grails-app/utils/com/deluan/grails/codecs
folder as
PermalinkCodec.groovy
Read the manual for more info on how to use codecs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment