37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
# File 'lib/acts_as_permalink.rb', line 37
def build_permalink
config = self.class.base_class.acts_as_permalink_config
text = self.public_send(config.from)
text = [self.class.base_class.to_s, rand(10000)].join(config.separator) if text.blank?
text = text.to_permalink(separator: config.separator, max_length: config.max_length)
conditions = {}
conditions[config.scope] = self.public_send(config.scope) if config.scope.present?
if self.class.base_class.where(conditions.merge(config.to => text)).any?
candidate_text = nil
(1..999999).each do |num|
suffix = "#{ config.separator }#{ num }"
candidate_text = [text[0...(config.max_length - suffix.length)], suffix].join("")
break unless self.class.base_class.where(conditions.merge(config.to => candidate_text)).any?
end
text = candidate_text
end
text
end
|