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.4.27 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.4 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.26 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.3 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.25 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.2 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.24 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.1 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.23 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.22 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.0 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.21 app/queries/workarea/find_unique_slug.rb
workarea-core-3.5.0.beta.1 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.20 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.19 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.18 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.17 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.16 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.15 app/queries/workarea/find_unique_slug.rb
workarea-core-3.4.14 app/queries/workarea/find_unique_slug.rb