Spaces inserted in browser in <pre> with Rails - ruby-on-rails

A simple test case:
<% content = "<pre>a\nb</pre>" %>
<%= raw content %>
Browser Screenshot, with inserted spaces on second line:
Here's where it gets interesting. In rails:
raw(content).size # => 14 (correct)
But, in JS:
$("pre").html().length // => 13 (should be 3)

Any chance you are using HAML for your layout? If so, that would explain it as HAML will indent things for you. You can use HAML's ~ to get around this.
See: http://haml.info/docs/yardoc/file.REFERENCE.html#tilde

Related

Can't render line breaks in Rails with simple_format

I'm aware that in order to render \r\n I need to use simple_format, however it doesn't work on my posts that I migrated from WordPress. I tried many solutions including regex to replace \r\n with break tags, but it didn't help either. I still see on the screen all the line breaks printed out as text and not rendered.
Here is what I tried:
<%= simple_format(#post.body) %>
<%= simple_format(#post.body.gsub(/(?:\n\r?|\r\n?)/, '<br>')) %>
If I just do something like below it will work.
<%= simple_format "<h1>Briefed while smartwatch firm Pebble lays off 25% of its staff</h1> -\r\n\r\n \r\n <p>hello</p>" %>
I have no idea what am I doing wrong.
Try following, it should works for you, I have tested, its working
> "\n\r".gsub(/[\r\n]+/, '<br>') => "<br>"
> "\r\n".gsub(/[\r\n]+/, '<br>') => "<br>"
In your case
(#post.body.gsub(/[\r\n]+/, '<br>')
I finally solved it using an SQL query:
UPDATE posts SET body = REPLACE(body, '\r\n', '<br>');
Don't know why Rails gsub didn't work.
Edit:
Looks like my regex was wrong. This solves it too:
<%= simple_format(#post.body.gsub(/\\r\\n/, "\n")) %>

Excess spaces wile rendering multiline string in Rails 5

I end up with strange bug (feature?):
Here is how test.html.erb file looks like:
<textarea><%= "a\nb\nc" %></textarea>
and in rendered textarea I expect something like that:
a
b
c
But I got:
Where these excess spaces came from?
Rails 5.0.0.beta2
UDP: I should mention it before, but I have the same problem while using f.text_area inside of form_for block. It looks like:
.form
=form_for article do |f|
.form-group
=field_label f, :text, true
=f.text_area :text, class: %w(form-control), rows: 20, placeholder: t('placeholder.article_text')
(HAML)
I end up with it, and just simplified the exploit to simple erb file with one string
UDP2:
Here how it looks with simple_format: <textarea><%= simple_format("a\nb\nc") %></textarea>
I should clearify some thing: this textarea is used to edit article text. And then it (text) will be processed with markdown processor (RDiscount) before appears in html page. I have no any idea, why I should use simple_format to display raw text in textarea and why this
should became this
after save?
In HAML, use
~ f.text_area :text
instead of
= f.text_area :text
The ~ operator suppresses "pretty" newlines in HAML, which is useful with TEXTAREA and PRE tags. See Whitespace preservation in HAML for more information.
<textarea><%= "a\r\nb\r\nc" %></textarea>
\n is new line it will take to next line at same position where you was in previous line \r is carriage return mean move to start of line.
But I wont recommend this approach You should use <br/> tag instead
so use
<textarea><%= WhatEverTheTextIs.gsub(/\n/, '<br/>').html_safe %></textarea>
This will replace all new line characters to <br> tag
One more easy solution is to use simple_format i-e:
<textarea><%= simple_format(YOUR_TEXT_HERE) %></textarea>
UPDATE
Here is the code to use for form helper
.form
=form_for article do |f|
.form-group
=field_label f, :text, true
=f.text_area :text,:value=>simple_format(article.text), class: %w(form-control), rows: 20, placeholder: t('placeholder.article_text')
I just ran into the exact same problem. It all comes down to whitespace in your templates and layouts. In my case my main application is using HAML and has an application.html.haml with a section like so
#content.container{tabindex: "-1"}
.row
- if content_for?(:left_nav)
.col-md-3.sidebar
= yield(:left_nav)
.col-md-9
= flash_helper
= yield
%footer
= render :partial => 'shared/footer'
That's at least 10 spaces before the "yield" of the main content.
Then I was using a view from a gem that was in ERB, not HAML. But, since my main application layout is HAML, the view rendering/handling goes through the HAML renderers. HAML has dealt with whitespace and texareas already, but when the final and complete view is rendered, all of the extra whitespace from the main layout is included in the html and causes the content of the textarea to be indented.
Why is the first row not indented? Because the HAML "preserve" function cleans up the whitespace for the first row in the text area. See https://github.com/haml/haml/issues/516.
For me, the easy fix is to configure HAML to use "ugly" mode. This gets rid of all the leading whitespace when rendering the views. There is more about "ugly" mode and newlines in textareas in the HAML FAQ. To configure HAML to use ugly mode:
To improve performance, Haml defaults to {Haml::Options#ugly "ugly" mode} in Rails apps running in production. Ugly mode is when whitespace is stripped out, and this can cause issues occassionally.
If you are using Rails, you can change the default behaviour by creating a config/initializers/haml.rb file and adding in the following line.
Haml::Template.options[:ugly] = true
Links I found helpful while researching this:
https://github.com/haml/haml/issues/643
ERB view embedded in a Haml layout: what to do about whitespace now? (although the proposed solution didn't work for me b/c the ERB view would always be picked up before the HAML view)
https://github.com/haml/haml/blob/master/lib/haml/buffer.rb (fix_textareas)
https://github.com/haml/haml/blob/master/lib/haml/helpers.rb (specifically the preserve method)
My versions are Rails 4.2.6 and HAML 4.0.7

How to prevent Rails from showing an empty line in the source code if condition is false?

In my Rails 4 app I have a TagHelper with this function:
def robots_tag
if important_page?
tag(:meta, :name => "robots", :content => "dofollow")
end
end
In my main layout I am using it like this:
<head>
<%= robots_tag %>
</head>
How can I prevent Rails from showing an empty line in the source code if important_page? is false?
Thanks for any help.
Try adding a minus sign at the end of the erb tag:
<%= robots_tag -%>
Just out of interest, why do you want to get rid of the newline? Even if it was in the body it wouldn't affect the result (visible to the user at least); in the head it seems even less important.
There's no way within the <%= %>-Statement to 'remove' the empty line, because there's a newline character just before (in the HTML, after the <head>-tag). If you really want to avoid an empty line, you need to remove this character by putting the ruby-tag/s right after the <head>-tag (the following code assumes the test for important_page? is removed from the method):
<head><% if important_page? %>
<%= robots_tag %><% end %>
</head>
(Side-note regarding the first answer: while the minus sign does remove the newline character, it doesn't remove the leading spacing, which results in just a different kind of ugly source code)

html_safe in ruby on rails not working

I'm using ruby 2.0.0
This is my controller..
#mail_msg = #store_items.where(id: params[:button_id]).first.email_confirmation_text
p "-------------------------"
p #mail msg
p #mail_msg.html_safe
This is my console(terminal) output
"-------------------------"
"<p>You have purchased Spice It Up. Points have been redeemed from your main account.</p>"
"<p>You have purchased Spice It Up. Points have been redeemed from your main account.</p>"
And what im getting in my console is the same. I cant escape the html tags.
Update
I have this value in my view..
in my view page
<%= #mail_msg.html_safe %>
Still its not working..
Please help
Try these one may will help you
strip_tags("Strip <i>these</i> tags!")
# => Strip these tags!
strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
# => Bold no more! See more here...
strip_tags("<div id='top-bar'>Welcome to my website!</div>")
# => Welcome to my website!enter code here
html_safe and raw work in views, use
<%= raw #mail_msg %>
or
<%= #mail_msg.html_safe %>

Including contents of a variable inside a Haml filter

How to make article.content filtered by :textile ?
- #articles.each do |article|
%article.post
%header=article.name
%p
:textile
=article.content
%footer
the output
<article class="post">
<header>game</header>
<p>
</p><p>=article.content</p>
<p></p>
<footer></footer>
</article>
Inside a Haml filter you use String interpolation to include Ruby code in your markup. For example:
require 'haml'
#x = 42
Haml::Engine.new("%p= #x").render(self) #=> "<p>42</p>\n"
Haml::Engine.new(":textile\n\t= #x").render(self) #=> "<p>= #x</p>\n"
Haml::Engine.new(":textile\n\t\#{#x}").render(self) #=> "<p>42</p>\n"
#content = "alpha\n\n#hi **mom**"
Haml::Engine.new(":textile\n\t\#{#content}").render(self)
#=> "<p>alpha</p>\n<p>#hi <b>mom</b></p>\n"
Edit: My previous answer was misleading with respect to newlines in the content, due to my flawed testing. As seen above, newlines in included content are handled fine directly.
As such, your Haml template should simply look like this:
- #articles.each do |article|
%article.post
%header=article.name
:textile
#{article.content}
%footer
Note that I've removed your %p tag surrounding your markup, as Textile introduces its own paragraph wrappers (even for single-line content).
Your syntax seems fine, if everything else is getting rendered properly maybe it's a gem issue. Do you have RedCloth installed?
Edit: On second thought, what does the second line do? It might be the cause of your problem since I don't think %article.post is proper HAML syntax and the :textile filter is inside it

Resources