0

Has anyone ever used random_slug (https://github.com/josei/random_slug) for friendly_id? It was last updated 5 years ago so I'm not sure if it's a waste of time to try it out or even if there is a better solution?

Basically I have friendly_id working in terms of it picks up the title of my posts and I have a scope so those posts are unique to the user, but I would very much like those posts to be a randomly generated URL something similar to YouTube URL's I suppose -- is this possible with friendly ID or am I going about this the wrong way and is there something else that would make my life 100x easier?

7urkm3n
  • 6,054
  • 4
  • 29
  • 46
Stuart Pontins
  • 285
  • 4
  • 14

2 Answers2

5

That plugin won't work, at least not by itself. It was designed as a rails 2 plugin which are incompatible with today's gems - but if you look at it's lib, ALL its doing is generating a random string, which as was pointed out in comment you can do using an SHA1 digest. I like secure random. (same concept)

You model would look something like this

class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :generated_slug, use: :slugged
  def generated_slug
    require 'securerandom' 
    @random_slug ||= persisted? ? friendly_id : SecureRandom.hex(15) 
  end
end
trh
  • 7,186
  • 2
  • 29
  • 41
0

You can use this way, passing title and id of each post, it will generate you new uniq slug even the title will be same, cause of passing extra id of post.

Make sure use your own column name title or smth else...

class Post < ActiveRecord::Base
  extend FriendlyId
  friendly_id :slugging, use: [:slugged, :history, :finders]

    def slugging
        Digest::SHA1.hexdigest("#{title} #{id}")[0..8]
    end
end
7urkm3n
  • 6,054
  • 4
  • 29
  • 46