Skip to content

Commit

Permalink
Added the possiblity to disable smart truncate (with the exception of… (
Browse files Browse the repository at this point in the history
#75)

* Add docs to EnableSmartTruncate

Co-authored-by: Aymen Ben Tanfous <aymen.bentanfous@cimpress.com>
Co-authored-by: Dobrosław Żybort <matrixik@gmail.com>
  • Loading branch information
3 people committed Sep 27, 2022
1 parent d311996 commit 452645f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 11 deletions.
12 changes: 10 additions & 2 deletions slug.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,17 @@ var (
CustomRuneSub map[rune]string

// MaxLength stores maximum slug length.
// It's smart so it will cat slug after full word.
// By default slugs aren't shortened.
// If MaxLength is smaller than length of the first word, then returned
// slug will contain only substring from the first word truncated
// after MaxLength.
MaxLength int

// EnableSmartTruncate defines if cutting with MaxLength is smart.
// Smart algorithm will cat slug after full word.
// Default is true.
EnableSmartTruncate = true

// Lowercase defines if the resulting slug is transformed to lowercase.
// Default is true.
Lowercase = true
Expand Down Expand Up @@ -108,12 +112,16 @@ func MakeLang(s string, lang string) (slug string) {
slug = strings.ToLower(slug)
}

if !EnableSmartTruncate {
slug = slug[:MaxLength]
}

// Process all remaining symbols
slug = regexpNonAuthorizedChars.ReplaceAllString(slug, "-")
slug = regexpMultipleDashes.ReplaceAllString(slug, "-")
slug = strings.Trim(slug, "-_")

if MaxLength > 0 {
if MaxLength > 0 && EnableSmartTruncate {
slug = smartTruncate(slug)
}

Expand Down
27 changes: 18 additions & 9 deletions slug_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,20 +278,29 @@ func TestSubstituteRuneLang(t *testing.T) {

func TestSlugMakeSmartTruncate(t *testing.T) {
testCases := []struct {
in string
maxLength int
want string
in string
maxLength int
want string
smartTruncate bool
}{
{"DOBROSLAWZYBORT", 100, "dobroslawzybort"},
{"Dobroslaw Zybort", 100, "dobroslaw-zybort"},
{"Dobroslaw Zybort", 12, "dobroslaw"},
{" Dobroslaw Zybort ?", 12, "dobroslaw"},
{"Ala ma 6 kotów.", 10, "ala-ma-6"},
{"Dobrosław Żybort", 5, "dobro"},
{"DOBROSLAWZYBORT", 100, "dobroslawzybort", true},
{"Dobroslaw Zybort", 100, "dobroslaw-zybort", true},
{"Dobroslaw Zybort", 12, "dobroslaw", true},
{" Dobroslaw Zybort ?", 12, "dobroslaw", true},
{"Ala ma 6 kotów.", 10, "ala-ma-6", true},
{"Dobrosław Żybort", 5, "dobro", true},
{"Long branch-name", 14, "long-branch-na", false},
{"Long branch-name", 12, "long-branch", false},
}

for index, smstt := range testCases {
MaxLength = smstt.maxLength
if smstt.smartTruncate {
EnableSmartTruncate = true
} else {
EnableSmartTruncate = false
}

got := Make(smstt.in)
if got != smstt.want {
t.Errorf(
Expand Down

0 comments on commit 452645f

Please sign in to comment.