Class: Workarea::FindUniqueSlug

Inherits:
Object
  • Object
show all
Defined in:
app/queries/workarea/find_unique_slug.rb

Instance Method Summary collapse

Constructor Details

#initialize(navigable, original_slug) ⇒ FindUniqueSlug

Returns a new instance of FindUniqueSlug.



3
4
5
6
# File 'app/queries/workarea/find_unique_slug.rb', line 3

def initialize(navigable, original_slug)
  @navigable = navigable
  @original_slug = original_slug
end

Instance Method Details

#existing_slugsObject



21
22
23
24
25
26
27
28
29
# File 'app/queries/workarea/find_unique_slug.rb', line 21

def existing_slugs
  @existing_slugs ||=
    @navigable
      .class
      .all
      .except(@navigable.id)
      .where(slug: pattern)
      .pluck(:slug)
end

#patternObject



31
32
33
# File 'app/queries/workarea/find_unique_slug.rb', line 31

def pattern
  @pattern ||= /^#{::Regexp.escape(@original_slug)}(?:-(\d+))?$/
end

#slugObject



8
9
10
11
12
13
14
15
16
17
18
19
# File 'app/queries/workarea/find_unique_slug.rb', line 8

def slug
  if existing_slugs.count > 0
    existing_slugs.sort! do |a, b|
      (pattern.match(a)[1] || -1).to_i <=> (pattern.match(b)[1] || -1).to_i
    end

    max_counter = existing_slugs.last.match(/-(\d+)$/).try(:[], 1).to_i
    @original_slug + "-#{max_counter + 1}"
  else
    @original_slug
  end
end