[RUBY] [Rails / simple_format] Helper method that reflects line breaks entered in the form

Status

demo


environment


Learned code

【reference】


This code

app/controllers/tasks_controller.rb


def show
  @task = Task.find(params[:id])
  @commits = @task.commits
end

erb:app/views/tasks/show.html.erb


<% @commits.each do |commit| %>
  <%= commit.content %>
<% end %>

With this display method, line breaks in commit.content are not reflected.

![demo](https://gyazo.com/924063a82ce7b72aadad02f9119c8bc3/raw)

This can be solved by using simple_format. Let's actually do it.


Use simple_format

erb:app/views/tasks/show.html.erb


<!-- simple_use format-->
<% @commits.each do |commit| %>
  <%= simple_format(commit.content) %>
<% end %>

** simple_format is a helper method ** that expresses line breaks with p tags and br tags. Just put the text you want to output in simple_format and you're done.

![demo](https://gyazo.com/4876cddd4f1ea1b982c00c2ce63bc223/raw)

Well, for the time being, the goal is achieved. However, there is a problem with this implementation. It is not "escaped" </ b>.

Let's take a closer look.


Allow to escape

Escape is a technique used in security measures. Simply put, it has the role of " eliminating the meaning of meaningful characters </ b>".

Let's look at it concretely. For example, suppose you enter the following.

demo

If you display this value without escaping it, it will be recognized as an "HTML tag" like this.

demo

In HTML, "<" is recognized as meaning "tag starts!". Therefore, if it is not escaped, it will be displayed as an h1 element.

This escape feature is granted by using <% =%> used in Rails views. However, if you use simple_format, you lose this functionality.

Therefore, when using simple_format, use the h option. This is a great way to add an escape feature to simple_format.

erb:app/views/tasks/show.html.erb



<%#use h option%>
<% @commits.each do |commit| %>
  <%= simple_format(h(commit.content)) %>
<% end %>

This will change the display as shown below.

demo

The meaning is deprived from "<" etc., and it is displayed as a simple symbol or character. Along with that, the letters have become smaller! (Enclosed in p tag)


Summary

  • I want to reflect the line break of form

  • Possible with simple_format!

  • Better to use h for security measures


It seems that simple_format is often used, but it is also a scary helper method if security measures are neglected. When using it, keep it in mind.

reference

Recommended Posts