Skip to content

Instantly share code, notes, and snippets.

@Merovex
Created August 21, 2022 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Merovex/9e9c626400c52e0f47d402f631268d81 to your computer and use it in GitHub Desktop.
Save Merovex/9e9c626400c52e0f47d402f631268d81 to your computer and use it in GitHub Desktop.
Create random slug
# frozen_string_literal: true
module Slug
extend ActiveSupport::Concern
def self.included(base)
base.extend ClassMethods
base.before_create :set_slug
end
def to_param
[title.to_s.parameterize, slug].join('-')
end
def set_slug
loop do
# self.slug = SecureRandom.base64(4).tr('+/=', '')
self.slug = SecureRandom.uuid.split('-').first
break unless self.class.find(slug)
end
end
module ClassMethods
# https://github.com/hungrymedia/superslug
# Overloading the default find_by method to allow for slug or id
def find_by!(arg, *args)
unless arg[:id].nil?
input = arg[:id]
if input.to_i.to_s != input.to_s
arg[:slug] = input.split('-').last
arg.delete(:id) # remove the ID from the hash since it's not a valid attribute
end
end
super
end
# https://github.com/hungrymedia/superslug
# Overloading the default find method to allow for slug or id
def find(input)
if input.instance_of?(Array)
super
else
input.to_i.to_s == input.to_s ? super : find_using_slug(input)
end
end
def find_using_slug(param)
slug = param.split('-').last || param
where(slug:).limit(1).first
end
# create random/unique slug
def unique_slug(key)
loop do
# slug = SecureRandom.base64(4).tr('+/=', '')
slug = SecureRandom.uuid.split('-').first
return slug unless where({ key.to_sym => slug }).exists?
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment