utils.rb 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. require 'jsonpath'
  2. require 'cgi'
  3. module Utils
  4. def self.unindent(s)
  5. s = s.gsub(/\t/, ' ').chomp
  6. min = ((s.split("\n").find {|l| l !~ /^\s*$/ })[/^\s+/, 0] || "").length
  7. if min > 0
  8. s.gsub(/^#{" " * min}/, "")
  9. else
  10. s
  11. end
  12. end
  13. def self.pretty_print(struct, indent = true)
  14. output = JSON.pretty_generate(struct)
  15. if indent
  16. output.gsub(/\n/i, "\n ").tap { |a| p a }
  17. else
  18. output
  19. end
  20. end
  21. def self.interpolate_jsonpaths(value, data)
  22. value.gsub(/<[^>]+>/).each { |jsonpath|
  23. Utils.values_at(data, jsonpath[1..-2]).first.to_s
  24. }
  25. end
  26. def self.recursively_interpolate_jsonpaths(struct, data)
  27. case struct
  28. when Hash
  29. struct.inject({}) {|memo, (key, value)| memo[key] = recursively_interpolate_jsonpaths(value, data); memo }
  30. when Array
  31. struct.map {|elem| recursively_interpolate_jsonpaths(elem, data) }
  32. when String
  33. interpolate_jsonpaths(struct, data)
  34. else
  35. struct
  36. end
  37. end
  38. def self.value_at(data, path)
  39. values_at(data, path).first
  40. end
  41. def self.values_at(data, path)
  42. if path =~ /\Aescape /
  43. path.gsub!(/\Aescape /, '')
  44. escape = true
  45. else
  46. escape = false
  47. end
  48. result = JsonPath.new(path, :allow_eval => false).on(data.is_a?(String) ? data : data.to_json)
  49. if escape
  50. result.map {|r| CGI::escape r }
  51. else
  52. result
  53. end
  54. end
  55. # Output JSON that is ready for inclusion into HTML. If you simply use to_json on an object, the
  56. # presence of </script> in the valid JSON can break the page and allow XSS attacks.
  57. # Optionally, pass `:skip_safe => true` to not call html_safe on the output.
  58. def self.jsonify(thing, options = {})
  59. json = thing.to_json.gsub('</', '<\/')
  60. if !options[:skip_safe]
  61. json.html_safe
  62. else
  63. json
  64. end
  65. end
  66. def self.pretty_jsonify(thing)
  67. JSON.pretty_generate(thing).gsub('</', '<\/')
  68. end
  69. end