Module: Slug::ClassMethods

Defined in:
lib/slug/slug.rb

Instance Method Summary collapse

Instance Method Details

#slug(source, opts = {}) ⇒ Object

Before create, Slug will generate and assign the slug if it wasn't explicitly set. Note that subsequent changes to the source column will have no effect on the slug. If you'd like to update the slug later on, call @model.set_slug



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/slug/slug.rb', line 18

def slug source, opts={}
  class_inheritable_accessor :slug_source, :slug_column
  include InstanceMethods
  
  self.slug_source = source
  
  self.slug_column = opts.has_key?(:column) ? opts[:column] : :slug

  uniqueness_opts = {}
  uniqueness_opts[:if] = opts[:validate_uniqueness_if] if opts.key?(:validate_uniqueness_if)
  
  validates                 self.slug_column, :presence => { :message => "cannot be blank. Is #{self.slug_source} sluggable?" }
  validates                 self.slug_column, :uniqueness => uniqueness_opts
  validates                 self.slug_column, :format => { :with => /^[a-z0-9-]+$/, :message => "contains invalid characters. Only downcase letters, numbers, and '-' are allowed." }
  before_validation :set_slug, :on => :create
end