Created
April 23, 2012 00:44
-
-
Save ncherro/2467835 to your computer and use it in GitHub Desktop.
Rails extension to add Permalink functionality to any model. To use, place in /app/models/extensions/permalink.rb
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
class ExampleModel < ActiveRecord::Base | |
# include the module | |
include Extensions::Permalink | |
# make sure there's a method named "unicode" that | |
# returns the string you'd like to sluggify | |
def unicode | |
self.name | |
end | |
end |
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
module Extensions | |
module Permalink | |
extend ActiveSupport::Concern | |
included do | |
before_validation :generate_permalink | |
validates :permalink, :uniqueness => true | |
def to_param | |
self.permalink | |
end | |
def generate_permalink | |
if self.new_record? || self.permalink_changed? | |
orig_p = self.permalink || self.unicode.parameterize | |
p = orig_p | |
i = 0 | |
while self.class.find_by_permalink(p) | |
p = "#{orig_p}-#{i}" | |
i += 1 | |
end | |
self.permalink = p | |
end | |
true | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The model must have a 'unicode' method, which returns the field to be used as the permalink.