Module: ActsAsSluggable

Extended by:
ActiveSupport::Concern
Defined in:
app/models/concerns/acts_as_sluggable.rb

Overview

ActsAsSluggable

This module automatically generates slugs based on the :title, :name, or :to_s field using a before_validation filter

Mark your model with ‘acts_as_sluggable’

and create the migration

structure do

slug     :string

end

You can override ActsAsSluggable

This module automatically generates slugs based on the :title, :name, or :to_s field using a before_validation filter

Mark your model with ‘acts_as_sluggable’

and create the migration

structure do

slug     :string

end

You can override def should_generate_new_slug?

new_record?

end

and def slug_source

return title if self.respond_to?(:title)
return name if self.respond_to?(:name)
to_s

end

This will work transparently with the ActsAsSiteSpecific, and should “just work” Please do not put any unique indexes on the slugs column. Or make it unique [:slug, :site_id]

Defined Under Namespace

Modules: ActiveRecord, ClassMethods, FinderMethods

Instance Method Summary collapse

Instance Method Details

#set_slugObject

Raises:

  • (StandardError)


73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'app/models/concerns/acts_as_sluggable.rb', line 73

def set_slug
  raise StandardError, "ActsAsSluggable expected a table column :slug to exist" unless respond_to?(:slug)

  new_slug = slug_source.to_s.try(:parameterize)

  if new_slug.present?
    while EffectiveSlugs.excluded_slugs.include?(new_slug) do
      new_slug << '-'.freeze << self.class.name.demodulize.parameterize
    end

    # TODO: Could make this a bit smarter about conflicts
    num_slugs = self.class.name.constantize.where(slug: new_slug).count
    num_slugs = self.class.name.constantize.where('slug LIKE ?', "#{new_slug}%").count if num_slugs > 0

    num_slugs == 0 ? self.slug = new_slug : self.slug = "#{new_slug}-#{num_slugs}"
  end

  true
end

#should_generate_new_slug?Boolean

Returns:

  • (Boolean)


99
100
101
# File 'app/models/concerns/acts_as_sluggable.rb', line 99

def should_generate_new_slug?
  slug.blank?
end

#slug_sourceObject



93
94
95
96
97
# File 'app/models/concerns/acts_as_sluggable.rb', line 93

def slug_source
  return title if respond_to?(:title)
  return name if respond_to?(:name)
  to_s
end

#to_paramObject



103
104
105
# File 'app/models/concerns/acts_as_sluggable.rb', line 103

def to_param
  (slug.present? rescue false) ? slug_was : super
end