I’ve released the polymorphic acts_as_permalinkable plugin that I developed for use with PLWire. To install:
./script/plugin discover \
http://plw.media.mit.edu:9090/repository/public/rails/plugins
./script/plugin install -x acts_as_permalinkable
./script/generate permalinkable_migration
rake migrate
Then just add the acts_as_permalinkable snippet to your models:
class Article < ActiveRecord::Base
acts_as_permalinkable
...
end
class Photo < ActiveRecord::Base
acts_as_permalinkable
...
end
When you save your model the permalink will automatically update as well. By default it uses a title attribute to create the slug and the created_on attribute for the date, but this is easily customized. For example to use it with the name attribute and the updated_at attribute:
acts_as_permalinkable \:on => :name,
:use_date => :updated_at
You can also provide a Proc that filters the permalinkable title field before it is turned into a slug. For example maybe you want to strip the tags and only take the first 20 characters:
acts_as_permalinkable \:on => :content,
:slug_modifier => lambda { |x|
x.gsub(/\<.+?\>/, "").strip[0..20]
}
Within your views you can link to the permalinks with a few url helper methods, url_for_permalink and link_to_permalink:
<%= url_for_permalink @article,
{:action => "permalink"},
{:class => "permalink",
:title => "Permalink for '#{@article.title}'"}
%>
<%= link_to_permalink "permalink", @article,
{:action => "permalink"},
{:class => "permalink",
:title => "Permalink for '#{@article.title}'"}
%>
And within your controller just use the find_permalinked method:
find_permalinked :slug => "this-is-a-slug",
:year => 2006,
:month => 8,
:day => 7
Underspecifying these parameters will return a collection for all matching records. Or if your parameters already have these values it is pretty easy:
find_permalinked params
You can add permalinks to existing records with the create_all_slugs singleton method. I use the console. For example, with an Article model:
Article.create_all_slugs
Hope it works out to be helpful for at least a few people out there.