0

I am using friendly_id for my rails app and noticed it put in a slug, word-for-word. I was wondering if there was a way to parse the slug from containing non-SEO relevant words such as "and" and "for". I have tried some REGEX but I'm not even sure if it applies to friendly_id.

In my Application Record (Model):

def to_slug(param=self.slug)

  # strip the string
  ret = param.strip

  #blow away apostrophes
  ret.gsub! /['`]/, ""

  # @ --> at, and & --> and
  ret.gsub! /\s*@\s*/, " at "
  ret.gsub! /\s*&\s*/, " and "

  # replace all non alphanumeric, periods with dash
  ret.gsub! /\s*[^A-Za-z0-9\.]\s*/, '-'

  # replace underscore with dash
  ret.gsub! /[-_]{2,}/, '-'

  # convert double dashes to single
  ret.gsub! /-+/, "-"

  # strip off leading/trailing dash
  ret.gsub! /\A[-\.]+|[-\.]+\z/, ""

  ret
end

I'm definitely no wiz at regular expression, I would love some help on this one, thanks.

P.S. Does my to_slug method even apply to friendly_id? I cant tell if the gem already performs all of these actions or not, thanks!

Jake
  • 1,086
  • 12
  • 38

1 Answers1

1

You are going to want to look at the friendly_id documentation where it gives you more information on Working With Slugs

Your model can look something like this (update it to fit your regex needs):

class SampleModel < ActiveRecord::Base
  extend FriendlyId
  friendly_id :custom_friendly_id

  # Insert more logic here
  def custom_friendly_id
    your_column.gsub! /\s*&\s*/, " and "
  end
end

I did this for a prior app and ran into a routing issue for older data. I ended up adding :slugged to my friendly_id command: friendly_id :custom_friendly_id, use: :slugged. Then ran a migration script to update the slug attribute in my model to correctly render the pages.

Hope this helps.

jdgray
  • 1,863
  • 1
  • 11
  • 19
  • Thank you, I'll review the "working with slugs" documents. Are the spaces before and after the replacement string crucial? – Jake Jun 23 '18 at 18:23
  • That is just an example how to customize your `friendly_id`. I didn't write out the full regex to meet your use case – jdgray Jun 23 '18 at 18:26