Last active
September 23, 2015 18:58
-
-
Save deluan/600968 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright 2010 Deluan Cotts ([email protected]) | |
* | |
* 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", "-") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use it in your Grails project, save it in
folder as Read the manual for more info on how to use codecs.