module Teams class GenerateSlug def self.call(team) new(team).call end def initialize(team) @team = team end def call base = @team.name.to_s.parameterize.presence || "squadra" slug = base n = 2 while conflict?(slug) slug = "#{base}-#{n}" n += 1 end slug end private def conflict?(slug) scope = Team.where(slug: slug) scope = scope.where.not(id: @team.id) if @team.persisted? scope.exists? end end end