event_headers_concern.rb 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # frozen_string_literal: true
  2. module EventHeadersConcern
  3. private
  4. def validate_event_headers_options!
  5. event_headers_payload({})
  6. rescue ArgumentError => e
  7. errors.add(:base, e.message)
  8. rescue Liquid::Error => e
  9. errors.add(:base, "has an error with Liquid templating: #{e.message}")
  10. end
  11. def event_headers_normalizer
  12. case interpolated['event_headers_style']
  13. when nil, '', 'capitalized'
  14. ->(name) { name.gsub(/[^-]+/, &:capitalize) }
  15. when 'downcased'
  16. :downcase.to_proc
  17. when 'snakecased'
  18. ->(name) { name.tr('A-Z-', 'a-z_') }
  19. when 'raw'
  20. :itself.to_proc
  21. else
  22. raise ArgumentError, "if provided, event_headers_style must be 'capitalized', 'downcased', 'snakecased' or 'raw'"
  23. end
  24. end
  25. def event_headers_key
  26. case key = interpolated['event_headers_key']
  27. when nil, String
  28. key.presence
  29. else
  30. raise ArgumentError, "if provided, event_headers_key must be a string"
  31. end
  32. end
  33. def event_headers_payload(headers)
  34. key = event_headers_key or return {}
  35. normalize = event_headers_normalizer
  36. hash = headers.transform_keys(&normalize)
  37. names =
  38. case event_headers = interpolated['event_headers']
  39. when Array
  40. event_headers.map(&:to_s)
  41. when String
  42. event_headers.split(',')
  43. when nil
  44. nil
  45. else
  46. raise ArgumentError, "if provided, event_headers must be an array of strings or a comma separated string"
  47. end
  48. {
  49. key => names ? hash.slice(*names.map(&normalize)) : hash
  50. }
  51. end
  52. end