can_uniq_name.rb 671 B

123456789101112131415161718192021222324252627282930313233
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module CanUniqName
  3. extend ActiveSupport::Concern
  4. # methods defined here are going to extend the class, not the instance of it
  5. class_methods do
  6. =begin
  7. generate uniq name (will check name of model and generates _1 sequenze)
  8. Used as before_update callback, no own use needed
  9. name = Model.generate_uniq_name('some name')
  10. returns
  11. result = 'some name_X'
  12. =end
  13. def generate_uniq_name(name)
  14. return name if !exists?(name: name)
  15. (1..100).each do |counter|
  16. name = "#{name}_#{counter}"
  17. break if !exists?(name: name)
  18. end
  19. name
  20. end
  21. end
  22. end