1
0

liquid_migrator.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. module LiquidMigrator
  2. def self.convert_all_agent_options(agent)
  3. agent.options = self.convert_hash(agent.options, {:merge_path_attributes => true, :leading_dollarsign_is_jsonpath => true})
  4. agent.save!
  5. end
  6. def self.convert_hash(hash, options={})
  7. options = {:merge_path_attributes => false, :leading_dollarsign_is_jsonpath => false}.merge options
  8. keys_to_remove = []
  9. hash.tap do |hash|
  10. hash.each_pair do |key, value|
  11. case value.class.to_s
  12. when 'String', 'FalseClass', 'TrueClass'
  13. path_key = "#{key}_path"
  14. if options[:merge_path_attributes] && !hash[path_key].nil?
  15. # replace the value if the path is present
  16. value = hash[path_key] if hash[path_key].present?
  17. # in any case delete the path attibute
  18. keys_to_remove << path_key
  19. end
  20. hash[key] = LiquidMigrator.convert_string value, options[:leading_dollarsign_is_jsonpath]
  21. when 'ActiveSupport::HashWithIndifferentAccess'
  22. hash[key] = convert_hash(hash[key], options)
  23. when 'Array'
  24. hash[key] = hash[key].collect { |k|
  25. if k.class == String
  26. convert_string(k, options[:leading_dollarsign_is_jsonpath])
  27. else
  28. convert_hash(k, options)
  29. end
  30. }
  31. end
  32. end
  33. # remove the unneeded *_path attributes
  34. end.select { |k, v| !keys_to_remove.include? k }
  35. end
  36. def self.convert_string(string, leading_dollarsign_is_jsonpath=false)
  37. if string == true || string == false
  38. # there might be empty *_path attributes for boolean defaults
  39. string
  40. elsif string[0] == '$' && leading_dollarsign_is_jsonpath
  41. # in most cases a *_path attribute
  42. convert_json_path string
  43. else
  44. # migrate the old interpolation syntax to the new liquid based
  45. string.gsub(/<([^>]+)>/).each do
  46. match = $1
  47. if match =~ /\Aescape /
  48. # convert the old escape syntax to a liquid filter
  49. self.convert_json_path(match.gsub(/\Aescape /, '').strip, ' | uri_escape')
  50. else
  51. self.convert_json_path(match.strip)
  52. end
  53. end
  54. end
  55. end
  56. def self.convert_make_message(string)
  57. string.gsub(/<([^>]+)>/, "{{\\1}}")
  58. end
  59. def self.convert_json_path(string, filter = "")
  60. check_path(string)
  61. if string.start_with? '$.'
  62. "{{#{string[2..-1]}#{filter}}}"
  63. else
  64. "{{#{string[1..-1]}#{filter}}}"
  65. end
  66. end
  67. def self.check_path(string)
  68. if string !~ /\A(\$\.?)?(\w+\.)*(\w+)\Z/
  69. raise "JSONPath '#{string}' is too complex, please check your migration."
  70. end
  71. end
  72. end