Better way than ''.html_safe when building html string in Rails?

277 views Asked by At

Typical pattern:

out = ''.html_safe # or ActiveSupport::SafeBuffer.new
out << content_tag(...) if foo
out << 'hello, 1 < 2' # will be escaped properly
out << content_tag(...) if bar

out

This works fine. Is there a nicer / shorter / better way than this, in particular calling ''.html_safe?

1

There are 1 answers

3
Matt Huggins On

I wouldn't upvote this, as I don't think it's really the answer you're looking for. But I figured I'd share some thoughts for consideration anyway.

This is actually probably harder to read, but I would be interested in seeing the results of a benchmark vs. the implementation used in your question.

out = "#{content_tag(...) if foo}" <<
      "hello, 1 < 2" <<
      "#{content_tag(...) if bar}"
out.html_safe

Also, I'm not familiar with the internals of how html_safe to know whether there's a difference in setting it as so initially vs. prior to returning. I'm guessing initial setting of html_safe would be faster since you're duplicating a zero-length string instead of a potentially long string, but for the sake of argument:

out = '' # or ActiveSupport::SafeBuffer.new
out << content_tag(...) if foo
out << 'hello, 1 < 2' # will be escaped properly
out << content_tag(...) if bar
out.html_safe

With that in mind, I would consider modifying my original code from above to even take it a step further:

"#{content_tag(...) if foo}".html_safe <<
"hello, 1 < 2" <<
"#{content_tag(...) if bar}"

Again, not very readable, but thought I'd throw it out there as food for thought.