Safe buffers and HEREDOCS

Hi!

I have some thoughts around the use of HEREDOCS to construct blocks of HTML in helpers (or decorators) I’d like some feedback on before filing a bug/feature request.

This kind of construct is bad:

#{content}
”.html_safe

We should really do this:

content_tag(:div, content, :class => ‘foo’)

or this:

html = “”.html_safe html << “

”.html_safe html << content html << “
”.html_safe

For longer blocks of HTML where there is a lot of logic required to get the pieces content going into it, both of the above quickly become unwieldy and hard to maintain.

Should we be able to do this:

[some logic that generates title, content, tags]

<<~HTML

#{title}

#{content}

#{tags}

HTML

…and have all interpolated content be marked as unsafe?

Doing this:

<<~HTML.html_safe

is a Bad Things to be avoided.

I’d be inclined to leave regular interpolated strings as is.

Could this be better dealt with with a new .unsafe method?

Cheers,

Richard

With the examples you have given, it seems that what it’s trying to is better accomplished with a small partial. You’d probably can even use render in helpers if that syntax would make you happier :slight_smile:

Or am I just missing the point here

I am thinking of cases where a lot of logic is required to determine what is in the HTML block, and generally I try to avoid having too much logic in views.

My use case is for a decorator method (but it could be a helper):

thing.as_digest(format, some_other_optional_params)

The format can be :extended, :standard and :compact. :standard is default.

The number of attributes shown, their format, and sometimes their position in the HTML block changes for each setting. The logic can be complex depending on settings in the underlying object, and I don't want to have all this in the view.

All objects in our system can have this method (Duck typing!) but I only add it when the amount of logic reaches a certain unhappiness threshold.

Richard