Created
January 12, 2012 22:00
-
-
Save mckinnsb/1603413 to your computer and use it in GitHub Desktop.
simple module for permalinks for models in rails
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 is a module for anything that can belong to a page - namely, MCOs | |
module Utilities | |
module Page | |
def self.included(base) | |
base.extend(ClassMethods) | |
base.class_eval do | |
include InstanceMethods | |
end | |
class << base | |
attr_accessor :permalink_field | |
end | |
end | |
module ClassMethods | |
def has_permalink(permalink_field) | |
before_save :prepare_permalink | |
self.permalink_field = permalink_field | |
end | |
end | |
module InstanceMethods | |
#Replace any character that is not an alphanumeric with an underscore | |
REPLACE_CHARS = /[^a-zA-Z0-9]/ | |
def prepare_permalink | |
base_string = self.send(self.class.permalink_field) | |
base_string = base_string.downcase.gsub(REPLACE_CHARS,"_").squeeze("_") | |
self[:permalink] = base_string | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment