concatenation of a html_safe string and a html_UNsafe string

Hi,
In console i tried the following:

("t".html_safe + "t2").html_safe?
=> true

Why is it returning true?

to my mind:
The concatenation of two Strings returns a new Object, which should
only be html_safe, if both parts are html_safe, otherwise html_UNsafe.

Hi,

In console i tried the following:

(“t”.html_safe + “t2”).html_safe?

=> true

Why is it returning true?

When you call .html_safe on the first String, it returns a SafeBuffer if it is a safe string.

Now, when you add another string, and if it is a plain string and you have not called .html_safe on it, the buffer escapes it first, then concatenates it.

This is why, you are getting these results.

to my mind:

The concatenation of two Strings returns a new Object, which should

only be html_safe, if both parts are html_safe, otherwise html_UNsafe.

Yes, you are right. When you do String1 + String 2, it returns a new String object. You can check it in irb, by calling .object_id on the String1, String2 and String1+String2.

For more information on this, refer to http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/.

> Hi,
> In console i tried the following:

> ("t".html_safe + "t2").html_safe?
> => true

> Why is it returning true?

> When you call .html_safe on the first String, it returns a SafeBuffer if it

is a safe string.

Now, when you add another string, and if it is a plain string and you have
not called .html_safe on it, the buffer escapes it first, then concatenates
it.

i looked up the implementation and it is exactly what you pointed out.
If someone wants to know what happens(activesupport-3.0.4/lib/
active_support/core_ext/string/output_safety.rb):

  def concat(value)
      if value.html_safe?
        super(value)
      else
        super(ERB::Util.h(value))
      end
    end

  def +(other)

      dup.concat(other)
    end

This is why, you are getting these results.

Thanks for your quick reply! Now it makes sense to me!

Hi,

In console i tried the following:

(“t”.html_safe + “t2”).html_safe?

=> true

Why is it returning true?

When you call .html_safe on the first String, it returns a SafeBuffer if it

is a safe string.

Now, when you add another string, and if it is a plain string and you have

not called .html_safe on it, the buffer escapes it first, then concatenates

it.

i looked up the implementation and it is exactly what you pointed out.

If someone wants to know what happens(activesupport-3.0.4/lib/

active_support/core_ext/string/output_safety.rb):

def concat(value)

  if value.html_safe?

    super(value)

  else

    super(ERB::Util.h(value))

  end

end

def +(other)

  dup.concat(other)

end

This is why, you are getting these results.

Thanks for your quick reply! Now it makes sense to me!

Happy to help. :slight_smile:

Also note that this is explained in the AS guide:

http://guides.rubyonrails.org/active_support_core_extensions.html#output-safety