Sha256: 343f395f2458cb8665340fe5444d59817fdb753a3d47c75f451401e0660574e7

Contents?: true

Size: 910 Bytes

Versions: 21

Compression:

Stored size: 910 Bytes

Contents

# frozen_string_literal: true

module NeetoCommonsBackend
  module Sluggable
    extend ActiveSupport::Concern

    included do
      def generate_slug(value_field, slug_field, relation = nil, only_content_is_present = false)
        value_slug = only_content_is_present ? "untitled" : self.send(value_field)&.parameterize
        return if value_slug.nil?

        query = relation || self.class
        latest_slug = query
          .where("#{slug_field} ~ ?", "^#{value_slug}$|^#{value_slug}-[0-9]+$")
          .unscope(:order).order("LENGTH(#{slug_field}) DESC", "#{slug_field}" => :desc)
          .first&.send(slug_field)

        slug_count = 0
        if latest_slug.present?
          slug_count = latest_slug.split("-").last.to_i
          slug_count = 1 if slug_count == 0
        end
        slug = slug_count.positive? ? "#{value_slug}-#{slug_count + 1}" : value_slug
      end
    end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
neeto-commons-backend-1.0.109 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.108 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.107 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.106 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.105 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.104 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.103 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.102 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.101 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.100 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.99 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.98 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.97 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.96 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.95 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.94 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.93 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.92 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.91 app/models/concerns/neeto_commons_backend/sluggable.rb
neeto-commons-backend-1.0.90 app/models/concerns/neeto_commons_backend/sluggable.rb