Skip to content

Instantly share code, notes, and snippets.

@123ish
Last active June 27, 2020 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 123ish/232bc3dd83ad40c068f00de6033177d4 to your computer and use it in GitHub Desktop.
Save 123ish/232bc3dd83ad40c068f00de6033177d4 to your computer and use it in GitHub Desktop.
Friendly_ID # /app/models/entry.rb
# /app/models/entry.rb
class Entry < ApplicationRecord
extend FriendlyId
friendly_id :entry_slug_input, use: [:history, :finders, :slugged]
after_commit :set_slug_with_id, on: :create
def entry_slug_input
"#{id}-#{name}"
end
def normalize_friendly_id(value)
slugstr = value
slugstr = slugstr.gsub(/\s+/,"-").downcase
slugstr = slugstr.gsub(/[:\/?#\[\]@!$&'()\*\+,;=<>\%{}|^\\~\.\"`_]/, "-")
slugstr = slugstr[0..70]
slugstr
end
def set_slug_with_id
self.save
end
private
def should_generate_new_friendly_id? #will change the slug if the name changed
self.id.present? && (slug.blank? || name_changed?)
end
def create_slug
return unless friendly_id
return if slugs.first.try(:slug) == friendly_id
# Allow reversion back to a previously used slug
relation = slugs.where(:slug => friendly_id)
if friendly_id_config.uses?(:scoped)
relation = relation.where(:scope => serialized_scope)
end
relation.delete_all if relation.present?
new_slug = FriendlyId::Slug.new(
sluggable_id: self.id,
sluggable_type: self.class.name.to_s,
slug: friendly_id
)
new_slug.scope = serialized_scope if friendly_id_config.uses?(:scoped)
new_slug.save
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment