Storing text with line break in javascript array - ruby-on-rails

I have a form where user can enter a note via a textfield.
When entering the note, user can press 'enter' to add line breaks and also the note entered can consist of multiple lines and it is stored in a table column of type varchar(2000) latin1_swedish_ci
On some other page, I am retrieving the notes from the database and storing them in an array. I am alerting the array contents to test whether everything is ok
My problem is that if the note spans on more than 1 line or contains line breaks, it does not seem to be stored in that array and the alert function does not alert anything for that particular note.
However, it is displayed properly if i display it using plain ruby code.
Here is an example of my code:
/********** loop through the resultset and store the values in the test_array **********/
<% #saved_note.each do |note| %>
<script type="text/javascript">
testarray[note_counter] = '<%= note.value %>';
alert(testarray[note_counter]);
note_counter++;
</script>
<%= note.value %>
<% end %>
Any suggestion is most appreciated.
Thanks a lot

If note.value spans more than one line, you will have this result:
testarray[note_counter] = 'Dear tanya,
how are you doing today?
sincerely,
user';
The problem here is that javascript doesn't support multiline strings without some massaging. If you've got any kind of newline characters hanging out in note.value, you'll want to escape them (see this example) before printing them out.

You can try
testarray[note_counter] = <%= raw note.value.to_json %>;
Personnaly I store that in AplicationHelper
def json value
raw value.to_json
end
and then in your view
testarray[note_counter] = <%= json note.value %>;

I'm unable to find an exact example of how I dealt with that in php, but the idea would be to try to parse all the symbols to their ansi code and check for the needed symbol like that. Just an idea tho.

Related

Displaying user input html with newlines

I have comments section in my application where users enter input in a text area. I want to prevent the line breaks they enter but also display html as a string. For example, if comment.body is
Hello, this is the code: <a href='foo'>foo</a>
Bye
I want it to be displayed just as above. The same with anything else, including iframe tags.
The closest I got is:
= simple_format(comment.body)
but it sanitizes html code and it's not displayed. Example: foo <iframe>biz</iframe> bar is displayed as:
foo biz bar
What should I do to achieve what I want?
Just use it without any method, it will be rendered as plain text:
= comment.body
Using your second example, the output will be:
foo <iframe>biz</iframe> bar
To make \n behave as <br>, you can use CSS:
.add-line {
white-space: pre-wrap;
}
And use it in your view:
.add-line = comment.body
Using your first example:
comment.body = "Hello, this is the code: <a href='foo'>foo</a>\n\nBye"
The output will be:
Hello, this is the code: <a href='foo'>foo</a>
Bye
Having done something similar in the past, I think you must first understand why HTML is sanitized from user input.
Imagine I wrote the following into a field that accepted HTML and displays this to the front page.
<script>alert('Hello')</script>
The code would execute for anyone visiting the front-page and annoyingly trigger a JS alert for every visitor.
Maybe not much of an issue yet, but imagine I wrote some AJAX request that sent user session IDs to my own server. Now this is an issue... because people's sessions are being hijacked.
Furthermore, there is a full JavaScript based exploitation framework called BeEF that relies on this type of website exploit called Cross-site Scripting (XSS).
BeEF does extremely scary stuff and is worth taking a look at when considering user generated HTML.
http://guides.rubyonrails.org/security.html#cross-site-scripting-xss
So what to do? Well if you checked in your DB you'd see that the tags are actually being stored, but like you pointed out aren't displayed.
You could .html_safe the content, but again I strongly advise against this.
Maybe instead you should write an alternative .html_safe method yourself, something like html_safe_whitelisted_tags.
As for removing newlines, you say you want to display as is. So replacing /n with <br>, as pointed out by Michael, would be the solution for you.
comment.body.gsub('\n', '<br />').html_safe_whitelisted_tags
HTML safe allows the html in the comment to be used as html, but would skip the newlines, so doing a quick replace of \n with <br /> would cover the new lines
comment.body.gsub("\n", "<br />").html_safe
If you want the html to be displayed instead of rendered then checkout CGI::escapeHTML(), then do the gsub so that the <br /> does not get escaped.
CGI::escapeHTML(comment.body).gsub("\n", "<br />")

Rails 4: how to insert line breaks in text_area?

I have created a blog in rails. I'm a beginner and got quite far, but now I'm stuck with a seemingly minor detail: I can't seem to format the posts (articles).
Here's the relevant part of my show.html.erb:
<p>
<strong>Content:</strong>
<%= simple_format (#article.content) %>
</p>
When I write something and insert html-tags, they are not recognized as such. What am I doing wrong?
Rails will automatically remove html tags to prevent someone from injecting code into your webpage (e.g. malicious javascript)
If your users cannot enter data into #article.content and it's always safe then you can flag it as safe usng the html_safe method.
<%= (simple_format (#article.content)).html_safe %>
Can you post the article content for reference? If I had to guess, I'd imagine Rails is escaping the html tags and inserting them as plain text (so the output looks like: Article content !
Take a look at Rails' helper methods like content_tag (http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag) and concat (http://apidock.com/rails/ActionView/Helpers/TextHelper/concat) and consider using those to help with generating the appropriate html tags.
An issue to be concerned with is who's going to be supplying the content. For example, if you're writing an application that other people will use, you want to make sure any html give you is escaped to avoid XSS attacks. In that case, you'll want to spend some time reading about how to properly sanitize user input.
You can now specify the tag it gets wrapped in (defaults to p) like so:
<%= simple_format (#article.content, {}, wrapper_tag: "div") %>
or
add white-space: pre-line style.
It will display \r or \n (enter) in user input as a new line.
for more info:
http://apidock.com/rails/v4.0.2/ActionView/Helpers/TextHelper/simple_format

Ruby on Rails: string method - how to recognize "enter" and re-display it?

I get the data from what other people inserted via a "textarea" in ruby on rails.
They must have clicked "enter" a couple of times. I saved this string data as a variable #input. But if I tried to display it by typing <%=#input%> , then all sentences are connected to together without a clear border that was meant to be there, seeming the enter is not recognized as an "enter".
I think there is a sure way to do it correctly and do you have any suggestion that I can display as the way that input users wanted to display? :)
Looking forward to seeing the opinion from the experts!!
What you're referring to is called newlines or line breaks. Rails got a helper method simple_format that will replace single newlines with <br /> tags and double newlines will wrap the previous string in a <p> tag
<%= simple_format #input %>
If you just want every newline character replaced with a break tag you could do it manually by substituting the \n character:
<%= #input.gsub("\n","<br />") %>

How to execute Ruby code in html content

I have html content that store in table. In that content I want to pass some ruby code
for example
temp = "<html><head>...</head><body>... <%= #something %> ...</body></html>"
then after I use temp.html_safe or raw temp
but #something is not printing
How can I do this ?
Please Help me
Just doing #temp = "<p>... #{#something} ...<p>" in your code and then in your view <%= #temp.html_safe %> should be enough.
This sort of functionality could get you in some dangerous waters. What if someone compromises your database, edits the code in that record to do something destructive, and then executes that code through your application?
You should look at using Liquid instead of executing ERB directly. (Also take a look at the accompanying Railscast.)

Rails DON'T sanitize

I am making a web app that integrates the Ace online IDE. A user enters an input through the Ace IDE which is then stored in a database. But when that is then rendered from the database Rails has done some sort of sanitization and the HTML tags are not loaded.
How do I explicitly tell Rails to leave all HTML tags in the tags and not format it (includes tabs and spaces)?
EDIT:
This is what the user inputs:
And this is what it outputs:
Try the raw method. This method outputs without escaping a string
you have to append .html_safe to any string you're returning to the view. By default Rails doesn't trust anything the user might have created.
So
<%= #my_source_code_from_the_db %>
Becomes
<%= #my_source_code_from_the_db.html_safe %>
As #Sam_D mentioned, another option is to wrap your string in a call to raw:
<%= raw(#my_source_code_from_the_db) %>
Turns out it was because I was using simple_format() when I removed that and just simply called <%= #lesson.lesson_content %> it rendered perfectly.

Resources