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
?
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.
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 ofhtml_safe
would be faster since you're duplicating a zero-length string instead of a potentially long string, but for the sake of argument:With that in mind, I would consider modifying my original code from above to even take it a step further:
Again, not very readable, but thought I'd throw it out there as food for thought.