Module: GoogleRest::Request::Util

Defined in:
lib/google_rest.rb

Constant Summary collapse

JSON_ESCAPE =
{ '&' => '\u0026', '>' => '\u003E', '<' => '\u003C', '=' => '\u003D' }

Class Method Summary collapse

Class Method Details

.json_escape(s) ⇒ Object

A utility method for escaping HTML entities in JSON strings. puts json_escape("is a > 0 & a < 10?")

=> is a \u003E 0 \u0026 a \u003C 10?



215
216
217
# File 'lib/google_rest.rb', line 215

def json_escape(s)
  s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] }
end

.json_recursive_unescape(data) ⇒ Object

A utility method for unescaping recursively HTML entities in JSON array or hash.



220
221
222
223
224
225
226
227
228
# File 'lib/google_rest.rb', line 220

def json_recursive_unescape(data)
  if data.is_a?(String)
    json_unescape(data)
  elsif data.is_a?(Hash)
    data.inject({}) { |hsh, (k,v)| hsh[k] = json_recursive_unescape(v);hsh }
  elsif data.is_a?(Array)
    data.collect { |v| json_recursive_unescape(v) }
  end
end

.json_unescape(s) ⇒ Object

A utility method for unescaping HTML entities in JSON strings. puts json_unescape("\u003E 0 \u0026 a \u003C 10?")

=> is a > 0 & a < 10?



208
209
210
# File 'lib/google_rest.rb', line 208

def json_unescape(s)
  JSON_ESCAPE.inject(s.to_s) { |str, (k,v)| str.gsub!(/#{Regexp.escape(v)}/i, k); str }
end