Browse files

AS guide: expands safe string docs regarding destructive methods, coe…

…rcion, copying, etc.
  • Loading branch information...
fxn committed Jun 17, 2011
1 parent f960cb2 commit 61fd39882560841be1f0bf38b0511d9e3d00d29f
Showing with 20 additions and 2 deletions.
  1. +20 −2 railties/guides/source/active_support_core_extensions.textile
@@ -1160,8 +1160,12 @@ h3. Extensions to +String+
h4. Output Safety
+h5. Motivation
Inserting data into HTML templates needs extra care. For example you can't just interpolate +@review.title+ verbatim into an HTML page. On one hand if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&". On the other hand, depending on the application that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the Security guide":security.html#cross-site-scripting-xss for further information about the risks.
+h5. Safe Strings
Active Support has the concept of <i>(html) safe</i> strings since Rails 3. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.
Strings are considered to be <i>unsafe</i> by default:
@@ -1187,8 +1191,6 @@ s # => "<script>...</script>"
It is your responsibility to ensure calling +html_safe+ on a particular string is fine.
-NOTE: For performance reasons safe strings are implemented in a way that cannot offer an in-place +html_safe!+ variant.
If you append onto a safe string, either in-place with +concat+/<tt><<</tt>, or with <tt>+</tt>, the result is a safe string. Unsafe arguments are escaped:
@@ -1229,6 +1231,22 @@ end
NOTE: Defined in +active_support/core_ext/string/output_safety.rb+.
+h5. Transformation
+As a rule of thumb, except perhaps for concatenation as explained above, any method that may change a string gives you an unsafe string. These are +donwcase+, +gsub+, +strip+, +chomp+, +underscore+, etc.
+In the case of in-place transformations like +gsub!+ the receiver itself becomes unsafe.
+INFO: The safety bit is lost always, no matter whether the transformation actually changed something.
+h5. Conversion and Coercion
+Calling +to_s+ on a safe string returns a safe string, but coercion with +to_str+ returns an unsafe string.
+h5. Copying
+Calling +dup+ or +clone+ on safe strings yields safe strings.
h4. +squish+
The method +squish+ strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:

0 comments on commit 61fd398

Please sign in to comment.