Module: Acts::Permalink::InstanceMethods

Defined in:
lib/acts_as_permalink.rb

Instance Method Summary collapse

Instance Method Details



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)

  # scope it if one is present
  conditions = {}
  conditions[config.scope] = self.public_send(config.scope) if config.scope.present?

  # Attempt to find the object by the permalink, and if so there is a collision and we need to de-collision it
  if self.class.base_class.where(conditions.merge(config.to => text)).any?
    candidate_text = nil

    # This will fail if you have a million records with the same name
    (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

#to_paramObject



28
29
30
# File 'lib/acts_as_permalink.rb', line 28

def to_param
  self.public_send(self.class.base_class.acts_as_permalink_config.to)
end


32
33
34
35
# File 'lib/acts_as_permalink.rb', line 32

def update_permalink
  self.public_send("#{ self.class.base_class.acts_as_permalink_config.to }=", build_permalink)
  true
end