refactor: added utility to convert title into slug
This commit is contained in:
17
community/lms/test_utils.py
Normal file
17
community/lms/test_utils.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import unittest
|
||||||
|
from .utils import slugify
|
||||||
|
|
||||||
|
class TestSlugify(unittest.TestCase):
|
||||||
|
def test_simple(self):
|
||||||
|
self.assertEquals(slugify("hello-world"), "hello-world")
|
||||||
|
self.assertEquals(slugify("Hello World"), "hello-world")
|
||||||
|
self.assertEquals(slugify("Hello, World!"), "hello-world")
|
||||||
|
|
||||||
|
def test_duplicates(self):
|
||||||
|
self.assertEquals(
|
||||||
|
slugify("Hello World", ['hello-world']),
|
||||||
|
"hello-world-2")
|
||||||
|
|
||||||
|
self.assertEquals(
|
||||||
|
slugify("Hello World", ['hello-world', 'hello-world-2']),
|
||||||
|
"hello-world-3")
|
||||||
30
community/lms/utils.py
Normal file
30
community/lms/utils.py
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import re
|
||||||
|
|
||||||
|
RE_SLUG_NOTALLOWED = re.compile("[^a-z0-9]+")
|
||||||
|
|
||||||
|
def slugify(title, used_slugs=[]):
|
||||||
|
"""Converts title to a slug.
|
||||||
|
|
||||||
|
If a list of used slugs is specified, it will make sure the generated slug
|
||||||
|
is not one of them.
|
||||||
|
|
||||||
|
>>> slugify("Hello World!")
|
||||||
|
'hello-world'
|
||||||
|
>>> slugify("Hello World!", ['hello-world'])
|
||||||
|
'hello-world-2'
|
||||||
|
>>> slugify("Hello World!", ['hello-world', 'hello-world-2'])
|
||||||
|
'hello-world-3'
|
||||||
|
"""
|
||||||
|
slug = RE_SLUG_NOTALLOWED.sub('-', title.lower()).strip('-')
|
||||||
|
used_slugs = set(used_slugs)
|
||||||
|
|
||||||
|
if slug not in used_slugs:
|
||||||
|
return slug
|
||||||
|
|
||||||
|
count = 2
|
||||||
|
while True:
|
||||||
|
new_slug = f"{slug}-{count}"
|
||||||
|
if new_slug not in used_slugs:
|
||||||
|
return new_slug
|
||||||
|
count = count+1
|
||||||
|
|
||||||
Reference in New Issue
Block a user