Created
February 19, 2010 17:10
-
-
Save DAddYE/308928 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# This module extend ActiveRecord. | |
# | |
# You need to to your model a column called +:permalink+ | |
# | |
# then use +has_permalink :title like: | |
# | |
# class Page < ActiveRecord::Base | |
# has_permalink :page | |
# end | |
# | |
module Permalink | |
module ClassMethods | |
def has_permalink(field) | |
include InstanceMethods | |
class_inheritable_accessor :permalink_field | |
write_inheritable_attribute :permalink_field, field | |
before_save :generate_permalink | |
end | |
end # ClassMethods | |
module InstanceMethods | |
def to_param | |
permalink | |
end | |
protected | |
def generate_permalink | |
self.permalink = read_attribute(permalink_field).downcase. | |
gsub(/\W/, '-'). | |
gsub(/-+/, '-'). | |
gsub(/-$/, ''). | |
gsub(/^-/, '') | |
end | |
end # InstanceMethods | |
end | |
ActiveRecord::Base.extend(Permalink::ClassMethods) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment