I'm getting some strings on human readable format, and those are gonna be titles of my wordpress posts. So, for generate the url for that post, I would like to know if there's some method for "urlize" a string in ruby. For example, if I have the string "Doing some test on my áccented string ", I would like to get "doing-some-test-on-my-accented-string" or do I have to write my own? Thanks in advance!
Asked
Active
Viewed 428 times
2
-
Pure ruby or RoR? In any case the keyword to google is “slug.” – Aleksei Matiushkin Nov 17 '17 at 16:23
-
If you're using ActiveSupport, String#parameterize is provided. Otherwise, you'll have to write your own, though it shouldn't be too hard (or you could just rip ActiveSupport's implementation - it's just a few lines). – Chris Heald Nov 17 '17 at 16:24
-
It's pure ruby... yeah, the annoying part is to handle accents :/. But thanks anyway! – Ronan Lopes Nov 17 '17 at 16:25
-
A more sophisticated one is in the `stringex` gem called `acts_as_url`. Check out the examples in [this answer](https://stackoverflow.com/a/4309257/182590). – Mark Thomas Nov 17 '17 at 18:21
3 Answers
2
After some suggestions, implemented my own method:
require 'i18n'
I18n.config.available_locales = :en
def urlize(string)
I18n.transliterate(string).squeeze.gsub(" ", "-").downcase
end
Hope this helps someone, thanks for the help!

Ronan Lopes
- 3,320
- 4
- 25
- 51
-
What's the squeeze for? And you might consider using tr instead of gsub for this particular use-case. – mwp Nov 17 '17 at 16:55
-
-
1Got it. It looks like ActiveSupport::Inflector.parameterize does the same thing. You can combine your `.squeeze.gsub(' ', '-')` into a single `.tr_s(' ', '-')` if you want to shave a few characters/operations. :) – mwp Nov 17 '17 at 17:01
-
2
I used i18n myself on occasion (eg here), but if you don't want to require yet another gem you could also use .tr
string_with_special_chars.tr(
"ÀÁÂÃÄÅàáâãäåĀāĂ㥹ÇçĆćĈĉĊċČčÐðĎďĐđÈÉÊËèéêëĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħÌÍÎÏìíîïĨĩĪīĬĭĮįİıĴĵĶķĸĹĺĻļĽľĿŀŁłÑñŃńŅņŇňʼnŊŋÒÓÔÕÖØòóôõöøŌōŎŏŐőŔŕŖŗŘřŚśŜŝŞşŠšſŢţŤťŦŧÙÚÛÜùúûüŨũŪūŬŭŮůŰűŲųŴŵÝýÿŶŷŸŹźŻżŽž",
"AAAAAAaaaaaaAaAaAaCcCcCcCcCcDdDdDdEEEEeeeeEeEeEeEeEeGgGgGgGgHhHhIIIIiiiiIiIiIiIiIiJjKkkLlLlLlLlLlNnNnNnNnnNnOOOOOOooooooOoOoOoRrRrRrSsSsSsSssTtTtTtUUUUuuuuUuUuUuUuUuUuWwYyyYyYZzZzZz")

peter
- 41,770
- 5
- 64
- 108
2
Won't give you as pretty results, but
require 'uri'
URI.escape(string.gsub(/\s+/, ?-)
For your example that gives
"Doing-some-test-on-my-%C3%A1ccented-string"

Max
- 21,123
- 5
- 49
- 71