# The Rails 3 implementation strips double quotes from the
# input for some reason:
# http://apidock.com/rails/v3.2.13/ERB/Util/json_escape/class
#
# The module below backports the non-insane Rails 4 implementation of json_escape:
# https://github.com/rails/rails/blob/924ef1c79a62ab97fe0c747395aad07d886a96e2/activesupport/lib/active_support/core_ext/string/output_safety.rb#L59
module Rails4JsonEscape

  JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003e', '<' => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' }
  JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u

  def json_escape(s)
    result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE)
    s.html_safe? ? result.html_safe : result
  end

  module_function :json_escape

end
