Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/scsmith/slugs_are_bad

A library for creating slugless urls in rails
https://github.com/scsmith/slugs_are_bad

Last synced: 17 days ago
JSON representation

A library for creating slugless urls in rails

Awesome Lists containing this project

README

        

SlugsAreBad
===========

Slugs are bad kids! Okaay.

They're not really bad but a number of solutions out there use both the models id and a slug (permalink) in the URL. Sometimes you just don't want a number crawling all over your url. This plugin acts as a drop in to your model to make its id in urls an attribute of your choice.

This plugin makes use of the to_params method of active record models so you will have to pass the whole object to any url methods not just the id. If you are already making use of rails' built in url methods and passing models as params then you shouldn't need to edit views or controllers.

This allows urls like the following
"pages/title-of-the-page"

instead of
"pages/123-title-of-the-page"

The downside of this approach however is that you must store a permalink in the database and it must be unique to each record. Don't forget to index it too!

Example
=======

app/models/user.rb
slugs_are_bad(:permalink_attribute, :generate_from)

# ie. slugs_are_bad(:permalink, :title)
# will automatically generate a id-free permalink from the title attribute and store it in the model.

Then in your view
link_to 'User', User.new(:name => 'foo bar') # nothing new needed here
# Generates /users/foo-bar instead of /users/1

Controllers
# create the user as usual
User.create!(:name => 'foo bar')

# To find the model with its nothing else is required
User.find(params[:id]) # nothing needed here (where id will be 'foo-bar')

# you could also manually specify the permalink in this instance if wanted.
User.create!(:name => 'foo-bar', :permalink => 'foo')

More Examples
=============

#replace the escape method so that it doesn't use the hyphens that come from parameterize
protected
def escape(string_to_escape)
super(string_to_escape).gsub('-', '_')
end

Todo
====
Tests are incomming, although the plugin has been tested in production use before it was a plugin there are no specific tests for the plugin yet.
Fork away and ping me with anything you want to add!

Shout Outs
==========

This plugin is adapted from two of the existing plugins acts_as_friendly by Chris Farms and permalink_fu by Technoweenie

Copyright (c) 2009 [Steve Smith], released under the MIT license