attributes_examples.rb 1.5 KB

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