diff options
Diffstat (limited to 'activesupport/lib/active_support/core_ext/string/output_safety.rb')
-rw-r--r-- | activesupport/lib/active_support/core_ext/string/output_safety.rb | 27 |
1 files changed, 21 insertions, 6 deletions
diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index b53929c2a3..addd4dab95 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -24,6 +24,7 @@ class ERB end end + # Aliasing twice issues a warning "discarding old...". Remove first to avoid it. remove_method(:h) alias h html_escape @@ -32,15 +33,23 @@ class ERB singleton_class.send(:remove_method, :html_escape) module_function :html_escape - # A utility method for escaping HTML entities in JSON strings. - # This method is also aliased as <tt>j</tt>. + # A utility method for escaping HTML entities in JSON strings + # using \uXXXX JavaScript escape sequences for string literals: + # + # json_escape("is a > 0 & a < 10?") + # # => is a \u003E 0 \u0026 a \u003C 10? + # + # Note that after this operation is performed the output is not + # valid JSON. In particular double quotes are removed: + # + # json_escape('{"name":"john","created_at":"2010-04-28T01:39:31Z","id":1}') + # # => {name:john,created_at:2010-04-28T01:39:31Z,id:1} + # + # This method is also aliased as +j+, and available as a helper + # in Rails templates: # - # In your ERb templates, use this method to escape any HTML entities: # <%=j @person.to_json %> # - # ==== Example: - # puts json_escape("is a > 0 & a < 10?") - # # => is a \u003E 0 \u0026 a \u003C 10? def json_escape(s) s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] } end @@ -92,7 +101,13 @@ module ActiveSupport #:nodoc: self end + def encode_with(coder) + coder.represent_scalar nil, to_str + end + def to_yaml(*args) + return super() if defined?(YAML::ENGINE) && !YAML::ENGINE.syck? + to_str.to_yaml(*args) end end |