Rails helper method to output html

Published on: Tuesday 10/10/2017

Author: Kelly-Ann
Project: Dog Informant
Topics:
Bird

So I'm working on an app project, "Dog Informant" which provides information on a wide variety (ok, only 10) of dog breeds.

Each dog's "show" page lists rankings for certain characteristics, such as "kid friendly" or "trainability." I wanted to represent the rankings, which are out of 5, as little Font Awesome paw icons.

Since I would be converting several characteristics into the icons, I wanted to put the logic into a helper method. So I got to work on my "convert_to_paws" method in helpers/dogs_helper.rb

My first problem was figuring out how to produce the paws x=ranking number of times. There are a few basic ways to do this in Ruby, but the cleanest way I found was the loop:
erb
x.times do
stuff to do
end

So I set up the following method:
ruby
def convert_to_paws(rank)
@text = ''"
rank.times do
@text += '<i class="fa fa-paw" aria-hidden="true"></i>'
end
end

Ruby returns the last variable, so I figured it would return my "@text" variable, which would be the paw times 5. Instead, all that was returned was the number 5. What went wrong?

It turns out that, for your protection, Rails assumes that html output is "unsafe" and won't render it. So since my method couldn't render the @text variable, instead it was rendering the number of times the loop ran.

There are several methods to tell Rails that your html output IS safe. The first method I came across was to add .html_safe to the end of the @text variable.

However, when I looked this method up in the Rails docs, the docs suggested using the sanitize() method instead.

My final working helper method to produce the Font Awesome icon x number of times is as follows:
ruby
def convert_to_paws(rank)
@text = ''"
rank.times do
@text += '<i class="fa fa-paw" aria-hidden="true"></i>'
end
sanitize(@text)
end

    

Leave a reply




Cancel