Safe buffers and HEREDOCS

33 views
Skip to first unread message

Richard Hulse

unread,
Apr 22, 2016, 6:59:12 AM4/22/16
to rubyonra...@googlegroups.com
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:

"<div class="foo">#{content}</div>".html_safe

We should really do this:

content_tag(:div, content, :class => 'foo')

or this:

  html = "".html_safe
  html << "<div class='foor'>".html_safe
  html << content
  html << "</div>".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
  <div>
    <h4>#{title}</h4>
    <p>#{content}</p>
    <p>#{tags}</p>
  </div>
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








 

Jarmo Isotalo

unread,
Apr 22, 2016, 12:33:23 PM4/22/16
to Ruby on Rails: Core
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 :)

Or am I just missing the point here

Richard Hulse

unread,
Apr 22, 2016, 3:38:37 PM4/22/16
to rubyonra...@googlegroups.com
On Fri, Apr 22, 2016 at 11:45 PM, Jarmo Isotalo <ja...@isotalo.fi> wrote:
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 :)

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




 
Reply all
Reply to author
Forward
0 new messages