Acts as Permalink

Build Status

Manages permalink field on an ActiveRecord model to be used in place of the id field in Rails.

Written by Kevin McPhillips ([email protected])

Installation

Using bundler, add to the Gemfile:

gem 'acts_as_permalink'

Or stand alone:

$ gem install acts_as_permalink

Usage

This gem works with ActiveRecord, and by convention looks for a title method and a permalink string field on the model:

And then just call it in your model:

class Post < ActiveRecord::Base
  acts_as_permalink
end

You can then use your link helpers normally:

post_path(@post) # "/post/the_name_of_post_here"

The title and permalink fields can be overridden with the following options:

from:        :title       # Name of the active record column or function used to generate the permalink
to:          :permalink   # Name of the column where the permalink will be stored
max_length:  60           # Maximum number of characters the permalink will be

So, for example you have want to store your permalink in a column called path_name and you want to generate your permalink using first and last name, and you want to restrict it to 40 characters, your model would look like:

class User < ActiveRecord::Base
  acts_as_permalink from: :full_name, to: :path, max_length: 40

  def full_name
    [first_name, last_name].join(" ")
  end
end

Tests

$ bundle exec rspec

Changelog

  • 0.4.1 -- Documentation improvements.

  • 0.4.0 -- Rails 4 support.

  • 0.3.2 -- Fixed regression in STI support.

  • 0.3.1 -- Rails 3.2 support.

  • 0.3.0 -- Fixed collision problem with single table inheritance models. Removed dependency on andand gem.

Contributing

  1. Fork it ( https://github.com/kmcphillips/acts_as_permalink/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request