payload_renderer.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # frozen_string_literal: true
  2. class Webhooks::PayloadRenderer
  3. class DocumentTraverser
  4. INT_REGEX = /[0-9]+/
  5. def initialize(document)
  6. @document = document.with_indifferent_access
  7. end
  8. def get(path)
  9. value = @document.dig(*parse_path(path))
  10. string = Oj.dump(value)
  11. # We want to make sure people can use the variable inside
  12. # other strings, so it can't be wrapped in quotes.
  13. if value.is_a?(String)
  14. string[1...-1]
  15. else
  16. string
  17. end
  18. end
  19. private
  20. def parse_path(path)
  21. path.split('.').filter_map do |segment|
  22. if segment.match(INT_REGEX)
  23. segment.to_i
  24. else
  25. segment.presence
  26. end
  27. end
  28. end
  29. end
  30. class TemplateParser < Parslet::Parser
  31. rule(:dot) { str('.') }
  32. rule(:digit) { match('[0-9]') }
  33. rule(:property_name) { match('[a-z_]').repeat(1) }
  34. rule(:array_index) { digit.repeat(1) }
  35. rule(:segment) { (property_name | array_index) }
  36. rule(:path) { property_name >> (dot >> segment).repeat }
  37. rule(:variable) { (str('}}').absent? >> path).repeat.as(:variable) }
  38. rule(:expression) { str('{{') >> variable >> str('}}') }
  39. rule(:text) { (str('{{').absent? >> any).repeat(1) }
  40. rule(:text_with_expressions) { (text.as(:text) | expression).repeat.as(:text) }
  41. root(:text_with_expressions)
  42. end
  43. EXPRESSION_REGEXP = /
  44. \{\{
  45. [a-z_]+
  46. (\.
  47. ([a-z_]+|[0-9]+)
  48. )*
  49. \}\}
  50. /iox
  51. def initialize(json)
  52. @document = DocumentTraverser.new(Oj.load(json))
  53. end
  54. def render(template)
  55. template.gsub(EXPRESSION_REGEXP) { |match| @document.get(match[2...-2]) }
  56. end
  57. end