Skip to content
Find file
Fetching contributors…
Cannot retrieve contributors at this time
87 lines (61 sloc) 2.63 KB

Sluggable

Description

This gem allows you to easily create slugs for your ActiveRecord models.

Installation

sudo gem install sluggable -s http://gemcutter.org

Usage

In `config/environment.rb`, add the following:

config.gem 'sluggable', :source => 'http://gemcutter.org'

Then, in your ActiveRecord model you just need to include the module and provide the column to use when generating the slug. For example, if we had a Post model with:

class Blog < ActiveRecord::Base
  # Columns:
  #  name: string
  #  slug: string

  include Sluggable
  slug_from :name

  before_validation :generate_slug

end

This sets it up so that the value of the `name` column is used as the source when generating the slug. The module also provides a private method (`generate_slug`) to generate and store the slug for this record. It requires that the table have a column called `slug` and is typically called in a lifecycle hook, though it can be called from anywhere you need it.

If you have a model that allows the same slug when scoped to another associated model, you can provide a parameter as part of the `slug_from` method:

class Post < ActiveRecord::Base
  # Columns:
  #  blog_id: integer
  #  title:   string
  #  body:    text
  #  slug:    string

  belongs_to :blog

  include Sluggable
  slug_from :title, :scope => :blog_id

  before_validation :generate_slug

end

This will allow the same slug to be generated for 2 posts each scoped to a different blog.

License

Copyright © 2009 Patrick Reagan (reaganpr@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Jump to Line
Something went wrong with that request. Please try again.