M
M
Maxim Valerievich2015-06-12 01:09:32
Ruby on Rails
Maxim Valerievich, 2015-06-12 01:09:32

Does anyone know why Rails render_to_string doesn't work as it should?

Hello. I'm trying to solve the problem for the third day. It is necessary to render the template on the rails into a string, there is a method render_to_string and render_to_body. It needs to be rendered because this line should be sent to the browser sse.write.

s = render_to_string(partial: 'comment', formats: [:html], locals: {comment: comment})
b = render_to_body(partial: 'comment', formats: [:html], locals: {comment: comment})

Neither render the template to a string. If you connect to the curl page, then the template comes as is, multiline. In the browser, if the output is displayed using js console.log, for example, then only the first line of the template comes. Well, it is correct, sse should send one whole line.
How the hell do you deal with this? =)
So far, only one idea has appeared and it works:
s = render_to_string(partial: 'comment', formats: [:html], locals: {comment: comment}).gsub("\n","")

Remove all newlines.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Vsk, 2015-06-12
@viktorvsk

I don’t see any problem at all in your question.
Although I’m not an expert in second rails, I think I won’t be wrong if I assume that from version 2.3.8, as you can see, if there were any shortcomings in this method, they have been fixed :)
What is the problem ? Is it that console.log() should output line breaks (\n) instead of line breaks, actually ? So the problem is that you are trying to interpret the right data incorrectly.
What exactly is your task now?

A
Alexey, 2015-06-13
@fuCtor

Here, either delete line breaks by hand, if I'm not mistaken in SSE, it is a field separator, or escape it. Or (IMHO the correct option) is to rewrite communication to JSON, and on the client side to render the received data into a template.
Here is a good example on this topic: www.sitepoint.com/mini-chat-rails-server-sent-events

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question