Created
October 10, 2009 10:05
-
-
Save satyatechsavy/206755 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def create_unique_permalink | |
return unless should_create_permalink? | |
if send(self.class.permalink_field).to_s.empty? | |
send("#{self.class.permalink_field}=", create_permalink_for(self.class.permalink_attributes)) | |
end | |
limit = self.class.columns_hash[self.class.permalink_field].limit | |
base = send("#{self.class.permalink_field}=", send(self.class.permalink_field)[0..limit - 1]) | |
counter = 1 | |
# oh how i wish i could use a hash for conditions | |
conditions = ["#{self.class.permalink_field} = ?", base] | |
unless new_record? | |
conditions.first << " and id != ?" | |
conditions << id | |
end | |
if self.class.permalink_options[:scope] | |
conditions.first << " and #{self.class.permalink_options[:scope]} = ?" | |
conditions << send(self.class.permalink_options[:scope]) | |
end | |
if should_create_unique_permalink? | |
while self.class.exists?(conditions) | |
suffix = "-#{counter += 1}" | |
conditions[1] = "#{base[0..limit-suffix.size-1]}#{suffix}" | |
send("#{self.class.permalink_field}=", conditions[1]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment