Howto enable permalinking in 3 steps

Posted by Jeremy Voorhis Tue, 09 Aug 2005 06:51:00 GMT

Or, My practical introduction to metaprogramming

UPDATE

At technoweenie’s request, I have packaged permalink as a gem. Download it here If you use the gem, you may omit lib/permalink.rb. Also, replace require 'permalink' with require_gem 'permalink'.


I wanted to give permalinking capabilities to several of my models, but didn’t want to repeat method definitions. This is what I came up with.

Add a field called ‘permalink’ to the table of the model you want permalinking for, and then add the following code to your project.

lib/permalink.rb
class ActiveRecord::Base

  def self.use_permalink( attr )
    self.class_eval <<-EOF, __FILE__, __LINE__
      before_save { |r| r.permalink = r.#{attr}.to_url }
    EOF
  end
end

class String
  # From Typo:
  # Converts a post title to its-title-using-dashes
  # All special chars are stripped in the process  
  def to_url
    result = self.downcase

    # replace quotes by nothing
    result.gsub!(/['"]/, '')

    # strip all non word chars
    result.gsub!(/\W/, ' ')

    # replace all white space sections with a dash
    result.gsub!(/\ +/, '-')

    # trim dashes
    result.gsub!(/(-)$/, '')
    result.gsub!(/^(-)/, '')

    result
  end
end
config/environment.
require 'permalink'
app/models/artist.rb (for example’s sake)
class Artist < ActiveRecord::Base
  has_many :albums

  use_permalink :name

  validates_uniqueness_of :name
end

Comments

Trackbacks

Use the following link to trackback from your own site:
http://www.jvoorhis.com/articles/trackback/5

(leave url/email »)