Question

I have a heredoc string

  html =<<EOF
    <span>
      Hello hello 123
    </span>
    <a>Link1</a>
    <a>Link2Link2</a>
EOF

If I say puts html, it will give html as it is, meaning with new lines which is fine. If I call p html I'll get the html without line breaks.

However, what I really need to do is to convert this html into picture and it should have line breaks. Here is how I do that:

kit  = IMGKit.new html, quality: 30
# using Magick::Image ......
# some code which is not important....
img.write("my_gif.gif")

It's almost fine except the fact that the result html, as I've already said, doesn't have line breaks, it has only one line:

<span>Hello hello 123</span><a>Link1</a><a>Link2Link2</a>

Of course, if I add <br /> tags, it all will be worked out. But I'm not able to do that for some reason, I want not to use <br /> and still have line breaks.

This is not the problem of IMGKit or Rmagic as I'm pretty sure.

So how do I achieve that?

Was it helpful?

Solution

I agree it is not a problem with IMGKit - it is doing what it is supposed to do - render the HTML. There is also nothing wrong with the heredoc, and nothing magical you can do with Ruby's representation of the HTML such that literal whitespace (spaces, tabs, newlines) in HTML source become visible when rendered.

The most common rendering of source whitespace by HTML viewers is that any length of pure whitespace (whether spaces, tabs, newlines or any combination) is rendered as a single space -> <- in the view. Additionally, whitespace between one element end and another starting is often completely ignored (although the rendering of the elements themselves may cause layout/spacing effects in the view).

You could, however, do something like this:

kit  = IMGKit.new html.gsub(/\n/,"<br/>"), quality: 30

and have line breaks rendered without adding <br/> to your heredoc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top