Rob Rob - 4 months ago 12
Ruby Question

Trying to copy what friendly_id does to turn a strong into a slug

I need to copy the way friendly_id changes text into slugs.

I was using this for my app

text = "random text"
text_gsubed = (value.gsub ' ', '-')
slug = text_gsubed.downcase


But recently I realised for text with non alphabetic or numeric characters it generates a different slug to what firendly_id generates e.g.

text = "random >> text"
text_gsubed = (value.gsub ' ', '-')
slug = text_gsubed.downcase


The slug the code above generates =
random->>-text


The slug feindly_id generates =
random-text


I though maybe they have a built in method you can use globally like
text.slug
or
text.friendly_id
if you have the gem installed but I cant see one. I also looked into their files to find the method that turns the string into a slug but cant find it.

How can I mimic what friendly_id is doing?

Answer

I'd probably look into the ActiveSupport::Inflections#parameterize.

In your case you should be able to call:

text.parameterize

If you want to combine with other parameters also, maybe id or something you could do:

[id, title, others].join(' ').parameterize
Comments