Created
October 31, 2017 10:21
-
-
Save paveltyk/0c608d3d5975587cd41a3c878562ac81 to your computer and use it in GitHub Desktop.
Slug generation for Elixir with Russian letters transliteration support.
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
defmodule Slugify do | |
@moduledoc """ | |
The main intent of this module is to be used in slug generation for URLs. | |
Supports russian transliteration. | |
""" | |
@char_mappings %{"а" => "a", "б" => "b", "в" => "v", "г" => "g", "д" => "d", "е" => "e", | |
"ё" => "e", "ж" => "j", "з" => "z", "и" => "i", "й" => "i", "к" => "k", "л" => "l", "м" => "m", | |
"н" => "n", "о" => "o", "п" => "p", "р" => "r", "с" => "s", "т" => "t", "у" => "y", "ф" => "f", | |
"х" => "h", "ц" => "ts", "ч" => "ch", "ш" => "sh", "щ" => "sch", "ъ" => "", "ы" => "y", | |
"ь" => "", "э" => "je", "ю" => "ju", "я" => "ja"} | |
@doc """ | |
Use this method to tranform any string to a url friendly slug. Usage example: | |
Slugify.to_slug("Hello из Беларуси!!!") #=> "hello-iz-belarysi" | |
""" | |
def to_slug(text) do | |
text | |
|> String.downcase | |
|> String.replace(~r/\W+/u, "-") | |
|> transliterate | |
|> String.replace(~r/^-+|-+$/u, "") # Remove trailing dashes | |
end | |
defp transliterate(text) do | |
Regex.replace(~r/[^-a-zA-Z0-9]/u, text, fn(ch) -> Map.get(@char_mappings, ch, "") end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment