ruby-on-railsfriendly-id

How to change slug before use in friendly_id gem?


I am trying to convert slugs to normal characters before using it in Friendly ID, but it does not work:

class CompanyJob < ApplicationRecord
  extend FriendlyId
  
  def self.convert_slug(title)
    n = title.downcase.to_s
    n.gsub! /[àáạãâậấẫầăặắằẵ]/, "a"
    n.gsub! /[đ]/, "d"
    n.gsub! /[èéẹẽêềếệễ]/, "e"
    n.gsub! /[óòọõôốồộỗơớợỡờ]/, "o"
    n.gsub! /[úùụũưứựừữ]/, "u"
    n.gsub! /[íịìĩ]/, "i"
    n.gsub! /[ýỵỹỳ]/, "y"
    return n
  end
        
  friendly_id CompanyJob.convert_slug(:title), use: :slugged

But, the resulting slug is the title unchanged by the convert function. Can anyone can help me solve this issue? Thanks so much!


Solution

  • You have a combination of two problems:

    1. You are literally passing the symbol :title to your .convert_slug method, so 100% of the time it just converts that to the string 'title' and returns it.
    2. The first parameter to the friendly_id thing is not the slug, it is the name (string or symbol) of a method that will be called to obtain the slug.

    So, because of #1 the first parameter is always the string 'title', which friendly_id then dutifully calls as a method and the result is your original title value.

    Wrapping your code in another method will get you what you want:

    class CompanyJob < ApplicationRecord
      extend FriendlyId
       
      def safe_slug
        slug = title.downcase.to_s
        # ... your .gsubs
        slug
      end
        
      friendly_id :safe_slug, use: :slugged