ruby-on-railsrubyfriendly-id

Why is my custom slug method skipping it's code?


I am trying to perform the following actions to alter my urls:

  1. parse instances of "an-" from my url
  2. remove a prefix of "the-" from my url if present.
class BlogPost < ApplicationRecord
  extend FriendlyId
  friendly_id :custom_slug, use: :history

  ...

  def custom_slug
    a = "#{title.to_s}"

    # goal is to remove the following words from url: an
    # the word being removed goes after "/\b and before \b/"
    # "#{title}".gsub! "/\ban\b/", ""
    a.gsub! "/\ban-\b/", ""

    # this should remove "the-" from the beginning of a slug if it's there
    if a.start_with?("the-")
      a.slice! "the-"
    end

    return a
  end

end

A title I'm trying to alter is "the example of an the post"

friendly_id converts to: /the-example-of-an-the-post

I want: /example-of-the-post

But my code to do this is not being executed and is just returning the original string. I know the .slice! portion of my code should work but I don't actually know if my code is correct or effective in this application of it.


Update

Following advice from @Schwern I came to some other conclusions to fix my issue:

a = "#{title.to_s}" to a = "#{title.to_s.downcase}"

Replaced faulty REGEX with a simpler solution:

if a.include?(" an ")
  a.gsub! " an ", " "
end

And directly from Schwern I was targeting something in the :slug and not the :title so it just had to change to this:

if a.start_with?("the ")
  a.slice! "the "
end

Solution

  • You're matching against the title of the post. Presumably the post is not titled the-example-of-an-the-post, that is how it would appear after conversion to a URL. The title is likely The example of an the post.