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.27 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.26 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.45 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.25 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.23 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.44 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.22 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.43 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.21 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.42 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.20 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.41 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.19 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.40 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.18 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.39 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.17 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.38 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.16 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.37 app/queries/workarea/find_unique_slug.rb