0

I have a Rails 4.2 application that has a rating system. I want to move the presenter logic into a helper. I want to show either a star or a half-star depending on whether the ranking is whole.

module ThingHelper
  def calculate_stars(thing)
    output = ""
    total = thing.overall_average

    thing.overall_average.ceil.times do |n| 
      if total >= 1
        output += content_tag(:i, "<%= fa_icon 'star' %>")
        total -= 1
      else  
        output += content_tag(:i, "<%= fa_icon 'star-half' %>")
      end
    end   
    return output
  end
end

In my erb template I have this:

<%= calculate_stars(thing).html_safe %>

However, it just lists out the strings like this: "<%= fa_icon 'star' %>". I have tried using raw as well as using concat instead of += but both attempted solutions just render a string.

I have also tried without the content_tag helper but that isn't working.

I have consulted the following: http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag, How to embed font-awesome icons into submit_tag, raw vs. html_safe vs. h to unescape html, and Ruby on Rails display half a star for a decimal rating, e.g. 4.5.

What am I missing? Thanks

Edit

I'm not convinced this can be done in the helper so I just had to put the logic in the view. Basically, I round and calculate the number of full stars then have a conditional to add another based upon rounding.

Community
  • 1
  • 1
user3162553
  • 2,699
  • 3
  • 37
  • 61

2 Answers2

3

There are two errors you're making that are super-small.

First, is in the parameters you're giving to content tag. Take a look at the documentation. In the first example...

content_tag(:p, "Hello world!")
 # => <p>Hello world!</p>

The string is what goes between the tags. However, Font Awesome icons need to be set as the class of the tag, with no content between the <i></i>.

Which means you need to pass content_tag an empty string and a hash...

<%= content_tag(:i, "", class: "fa-icon star") %>
=> "<i class="fa_icon star"></i>"

I know you're doing other things to multiply stars and whatnot. I think you'll be able to take it from here...

Lanny Bose
  • 1,811
  • 1
  • 11
  • 16
0

You don't need to declared a string for output.

module ThingHelper
  def calculate_stars(thing)
    total = thing.overall_average

    thing.overall_average.ceil.times do |n| 
      if total >= 1
        content_tag(:i, :class => "fa fa-list") do
        end
        total -= 1
      else  
        content_tag(:i, :class => "fa fa-list") do
        end
      end
    end   
  end
end

Then render on your erb:

<%= calculate_stars(thing) %>

Note that I am using bootstrap and glyphicons for my icon. Just change the icon class.

I have tried this on my development and produced this:

enter image description here