0
@@ -14,24 +14,61 @@ module PermalinkFu
0
- # Specifies the given field(s) as a permalink, meaning it is passed through PermalinkFu.escape and set to the permalink_field. This
0
- # class Foo < ActiveRecord::Base
0
- # # stores permalink form of #title to the #permalink attribute
0
- # has_permalink :title
0
- # # stores a permalink form of "#{category}-#{title}" to the #permalink attribute
0
- # has_permalink [:category, :title]
0
- # # stores permalink form of #title to the #category_permalink attribute
0
- # has_permalink [:category, :title], :category_permalink
0
- def has_permalink(attr_names = [], permalink_field = nil)
0
- permalink_field ||= 'permalink'
0
- before_validation { |record| record.send("#{permalink_field}=", Array(attr_names).collect { |attr_name| PermalinkFu.escape(record.send(attr_name).to_s) }.join('-')) if record.send(permalink_field).to_s.empty? }
0
+ def self.included(base)
0
+ base.extend ClassMethods
0
+ attr_accessor :permalink_attributes
0
+ attr_accessor :permalink_field
0
+ # Specifies the given field(s) as a permalink, meaning it is passed through PermalinkFu.escape and set to the permalink_field. This
0
+ # class Foo < ActiveRecord::Base
0
+ # # stores permalink form of #title to the #permalink attribute
0
+ # has_permalink :title
0
+ # # stores a permalink form of "#{category}-#{title}" to the #permalink attribute
0
+ # has_permalink [:category, :title]
0
+ # # stores permalink form of #title to the #category_permalink attribute
0
+ # has_permalink [:category, :title], :category_permalink
0
+ def has_permalink(attr_names = [], permalink_field = 'permalink')
0
+ self.permalink_attributes = Array(attr_names)
0
+ self.permalink_field = permalink_field
0
+ before_validation :create_unique_permalink
0
+ def create_unique_permalink
0
+ if send(self.class.permalink_field).to_s.empty?
0
+ send("#{self.class.permalink_field}=", create_permalink_for(self.class.permalink_attributes))
0
+ base = send(self.class.permalink_field)
0
+ conditions = ["#{self.class.permalink_field} = ?", send(self.class.permalink_field)]
0
+ conditions.first << " and id != ?"
0
+ while self.class.count(:all, :conditions => conditions) > 0
0
+ conditions[1] = "#{base}-#{counter += 1}"
0
+ send("#{self.class.permalink_field}=", conditions[1])
0
+ def create_permalink_for(attr_names)
0
+ attr_names.collect do |attr_name|
0
+ PermalinkFu.escape(send(attr_name).to_s)
Comments
No one has commented yet.