Module: WulffeldSlug::SlugInclude

Extended by:
ActiveSupport::Concern
Defined in:
lib/wulffeld_slug/slug_include.rb

Instance Method Summary collapse

Instance Method Details

#cb_make_slugObject



36
37
38
39
40
41
42
43
44
# File 'lib/wulffeld_slug/slug_include.rb', line 36

def cb_make_slug
  # NOTE: Uniqueness is not checked if slug is non-nil. You must ensure uniqueness yourself then.
  return unless slug.blank?

  slug_items = resolve_slug_items
  return if slug_items.blank?

  self.slug = to_unique_slug(slug_items)
end

#resolve_slug_itemsObject



46
47
48
# File 'lib/wulffeld_slug/slug_include.rb', line 46

def resolve_slug_items
  [*send(slug_config[:fields])].reject(&:nil?).map {|f| f.is_a?(String) ? f : send(f) }.flatten.reject(&:blank?)
end

#slug_unique?(slug) ⇒ Boolean

You may override this.

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/wulffeld_slug/slug_include.rb', line 24

def slug_unique?(slug)
  if new_record?
    !self.class.where(:slug => slug).first
  else
    if self.slug_config[:mongo]
      !self.class.where(:slug => slug).and(:_id.ne => self.id).first
    else
      !self.class.where(["slug = ? AND id <> ?", slug, self.id]).first
    end
  end
end

#to_paramObject



19
20
21
# File 'lib/wulffeld_slug/slug_include.rb', line 19

def to_param
  slug
end

#to_unique_slug(slug_items, n = nil) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/wulffeld_slug/slug_include.rb', line 50

def to_unique_slug(slug_items, n=nil)
  str_part = WulffeldSlug::PrepareString.new(slug_items, slug_config.merge(:kinds => (respond_to?(:slug_kinds) ? [*slug_kinds] : nil))).slug
  str_part = self.id.to_s if str_part.blank? && !self.new_record?

  loop do
    slug = [str_part, n].reject(&:blank?).join('-')
    return slug if !slug.blank? && slug_unique?(slug)

    # First loop we do some optimistic searching.
    if n.nil?
      # There's often a difference between adding a number to a slug where the string is present
      # and one where we only have the number for the final slug.
      # :blank_loop_start and :blank_loop_chunk helps speed up the looping on blank slugs.
      if str_part.blank?
        b = slug_config[:blank_loop_start]
      else
        b = slug_config[:loop_start]
      end

      last_b = nil
      loop do
        slug = [str_part, b].reject(&:blank?).join('-')
        if slug_unique?(slug) || b < 1
          last_b = b
          break if b < 1
        else
          n = last_b
          break
        end
        
        if str_part.blank? && slug_config[:blank_loop_chunk] && b - slug_config[:blank_loop_chunk] > slug_config[:blank_loop_chunk]
          b -= slug_config[:blank_loop_chunk]
        else
          b /= 2
        end
      end
    end
    n ||= 0
    n += 1
  end
end