attributes_examples.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. module Import
  3. module Helper
  4. class AttributesExamples
  5. attr_reader :examples, :enough, :max_unkown
  6. def initialize(&block)
  7. @max_unkown = 50
  8. @no_new_counter = 1
  9. @examples = {}
  10. @known = []
  11. # Support both builder styles:
  12. #
  13. # Import::Helper::AttributesExamples.new do
  14. # extract(attributes)
  15. # end
  16. #
  17. # and
  18. #
  19. # Import::Helper::AttributesExamples.new do |extractor|
  20. # extractor.extract(attributes)
  21. # end
  22. return if !block
  23. if block.arity.zero?
  24. instance_eval(&block)
  25. else
  26. yield self
  27. end
  28. end
  29. def extract(attributes)
  30. unknown = attributes.keys - @known
  31. return if !unknown?(unknown)
  32. store(attributes, unknown)
  33. @known.concat(unknown)
  34. @no_new_counter = 0
  35. end
  36. private
  37. def unknown?(unknown)
  38. return true if unknown.present?
  39. @no_new_counter += 1
  40. # check max 50 entries with no or no new attributes in a row
  41. @enough = @no_new_counter != 50
  42. false
  43. end
  44. def store(attributes, unknown)
  45. unknown.each do |attribute|
  46. value = attributes[attribute]
  47. next if value.nil?
  48. example = value.to_utf8(fallback: :read_as_sanitized_binary)
  49. example.gsub!(%r{^(.{20,}?).*$}m, '\1...')
  50. @examples[attribute] = "#{attribute} (e. g. #{example})"
  51. end
  52. end
  53. end
  54. end
  55. end