# 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