Skip to content

Instantly share code, notes, and snippets.

@mckinnsb
Created January 12, 2012 22:00
Show Gist options
  • Save mckinnsb/1603413 to your computer and use it in GitHub Desktop.
Save mckinnsb/1603413 to your computer and use it in GitHub Desktop.
simple module for permalinks for models in rails
#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