Module: PermalinkFor::SlugImpl

Extended by:
ActiveSupport::Concern
Defined in:
lib/permalink_for/slug_impl.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/permalink_for/slug_impl.rb', line 25

def build_permalink
  target_field_value = send(permalink_configuration[:target_field])

  return if permalink.present? || target_field_value.blank?
  permalink_base = I18n.transliterate(target_field_value).parameterize.downcase
  permalink_candidate = permalink_base
  generated_permalink = nil

  attempts_number = 100
  attempts = attempts_number
  while attempts > 0 && generated_permalink.nil?
    if self.class.find_by(permalink: permalink_candidate)
      attempts -= 1
      permalink_candidate = permalink_base + (attempts_number - attempts).to_s
    else
      generated_permalink = permalink_candidate
    end
  end

  fail 'Failed to generate permalink' if generated_permalink.nil?
  self.permalink = generated_permalink
end

#to_paramObject



20
21
22
23
# File 'lib/permalink_for/slug_impl.rb', line 20

def to_param
  return permalink if permalink.present?
  id
end