Module: Mongoid::Slug::ClassMethods

Defined in:
lib/mongoid/slug.rb

Instance Method Summary collapse

Instance Method Details

#find_by_slug(slug) ⇒ Object

Finds the document with the specified slug or returns nil.



55
56
57
# File 'lib/mongoid/slug.rb', line 55

def find_by_slug(slug)
  where(slug_name => slug).first rescue nil
end

#slug(*fields) ⇒ Object

Sets one ore more fields as source of slug.

By default, the name of the field that stores the slug is “slug”. Pass an alternative name with the :as option.

If you wish the slug to be permanent once created, set :permanent to true.

To index slug in a top-level object, set :index to true.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mongoid/slug.rb', line 25

def slug(*fields)
  options = fields.extract_options!

  self.slug_name      = options[:as] || :slug
  self.slug_scope     = options[:scope] || nil
  self.slugged_fields = fields

  if options[:scoped]
    ActiveSupport::Deprecation.warn <<-EOM

      The :scoped => true option is deprecated and now default for embedded
      child documents. Please use :scope => :association_name if you wish
      to scope by a reference association.
    EOM
  end

  field slug_name

  if options[:index]
    index slug_name, :unique => (slug_scope ? false : true)
  end

  if options[:permanent]
    before_create :generate_slug
  else
    before_save :generate_slug
  end
end