module TheFriendlyId::Base

Constants

SEPARATOR

Public Class Methods

friendly?(str) click to toggle source
# File lib/the_friendly_id.rb, line 21
def self.friendly? str
  Regexp.new("\\#{TheFriendlyId::Base::SEPARATOR}") =~ str
end
int?(str) click to toggle source
# File lib/the_friendly_id.rb, line 17
def self.int? str
  str.to_s.to_i.to_s == str
end
short?(str) click to toggle source
# File lib/the_friendly_id.rb, line 25
def self.short? str
  str =~ /^[A-Z]+[0-9]+$/mix
end

Public Instance Methods

build_short_id() click to toggle source
# File lib/the_friendly_id.rb, line 49
def build_short_id
  return unless self.short_id.blank?
  klass  = self.class.to_s.downcase.to_sym
  prefix = friendly_prefix[klass]

  # build short id
  prefix  ||= 'x'
  rnd_num   = 9999
  short_id  = [prefix, rand(rnd_num)].join

  # rebuild if find identically short_id
  try_counter = 0
  while self.class.where(short_id: short_id).first
    short_id = [prefix, rand(rnd_num)].join
    try_counter = try_counter + 1
    break if try_counter > (rnd_num/10)
  end

  # set short_id
  self.short_id = short_id
end
build_slugs() click to toggle source
# File lib/the_friendly_id.rb, line 71
def build_slugs
  unless self.title.blank?
    _slug = slug.blank? ? title : slug
    _slug = title if title_changed?
    _slug = slug  if slug_changed? && !slug.blank?

    self.slug        = uniq_slug(_slug)
    self.friendly_id = [self.short_id, self.slug].join TheFriendlyId::Base::SEPARATOR
  end
end
friendly_prefix() click to toggle source
# File lib/the_friendly_id.rb, line 38
def friendly_prefix
  {
    hub:    :h,
    page:   :p,
    post:   :pt,
    blog:   :b,
    recipe: :r,
    note:   :n
  }
end
to_param() click to toggle source
# File lib/the_friendly_id.rb, line 30
def to_param; self.slug end
uniq_slug(str) click to toggle source
# File lib/the_friendly_id.rb, line 82
def uniq_slug str
  _slug = str.to_s.to_slug_param

  10.times do |i|
    objs_with_this_slug = self.class.where(slug: _slug)
    break if objs_with_this_slug.size.zero?
    break if objs_with_this_slug.size == 1 && objs_with_this_slug.include?(self)
    _slug = [str, i.next].join('-').to_s.to_slug_param
  end

  _slug
end