Sha256: 85bad7498eb1b78e4536e7dd7605764a5220c9ce98cfa5603b6ef95fb401a6ce

Contents?: true

Size: 815 Bytes

Versions: 62

Compression:

Stored size: 815 Bytes

Contents

module Workarea
  class FindUniqueSlug
    def initialize(navigable, original_slug)
      @navigable = navigable
      @original_slug = original_slug
    end

    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

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

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

Version data entries

62 entries across 62 versions & 1 rubygems

Version Path
workarea-core-3.5.15 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.36 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.14 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.35 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.13 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.34 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.12 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.33 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.11 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.10 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.32 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.9 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.31 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.8 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.30 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.7 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.29 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.6 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.28 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.5 app/queries/workarea/find_unique_slug.rb