1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

AS guide: expands safe string docs regarding destructive methods, coercion, copying, etc.

This commit is contained in:
Xavier Noria 2011-06-17 10:57:33 +02:00
parent ba1b88fda6
commit 248552e324

View file

@ -1146,8 +1146,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:
@ -1173,8 +1177,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:
<ruby>
@ -1215,6 +1217,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: