diff --git a/slug.go b/slug.go index 14acce7..99520e7 100644 --- a/slug.go +++ b/slug.go @@ -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 @@ -102,12 +106,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) } diff --git a/slug_test.go b/slug_test.go index baace64..3f20d5f 100644 --- a/slug_test.go +++ b/slug_test.go @@ -266,20 +266,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(