acts_as_stubbable
Why?
I tend to use a lot of url-friendly strings for SEO in my web apps. Wanting to dry up my code, I created a module mixin for generating stubs, and turned it into a light-weight gem.
Installation
For Rails 3, in your Gemfile: gem 'acts_as_stubbable'
Usage
Let's pretend we have a column for our Thing class called name, which is a string. First in your ActiveRecord model, tell Stubbable which column should be used to generate the stub, i.e.
acts_as_stubbable :column => :name
So that your model looks like:
class Thing < ActiveRecord::Base
attr_accessible :name, :stub #for rails 3.2 onwards,
acts_as_stubbable :column => :name
end
Lastly, don't forget to create a migration for your model which adds the :stub column, i.e.
class AdStubToThings < ActiveRecord::Migration
def up
add_column :things, :stub, :string
end
def down
remove_column :things, :stub
end
end
Now, when a new Thing instance is created with a name, i.e.
t = Thing.new(:name => 'My name is Lionel Hutz aka Miguel Sanchez!')
t.save
puts t.stub
=> 'my-name-is-lionel-hutz-aka-miguel-sanchez'
you get a url-friendly string, with any special characters stripped and spaced turned into hyphens, using the built-in String.parameterize method.
Like the ads say, "It's that simple, it really is!"