Iggy
Iggy

Reputation: 5251

How to use rails helper method that takes in an icon as an argument?

I want to create a method that gives me star rating. The stars will be from fontawesome's star and star-half. I created the method below that takes in rating (float. 0.0 to 5.0 in 0.5 increments). Half-star will be <i class="fa fa-star-half" aria-hidden="true"></i> and star will be <i class="fa fa-star" aria-hidden="true"></i>. If rating is 3.5, it is expected to return (3 × star) + (1 × half-star).

def star_rating(rating, star, half_star)
  star = star
  half_star = half_star
  if ((rating % 1).round == 1) #ends with 0.5
    result = (rating - 0.5).round * star + half_star
  else
    result = rating * star
  end
  return result
end

I have never done something like this before. My initial thought was to put the star_rating() inside Ruby helper (posts_helper.rb in this case).

In post's view index.html.erb, I did <%= star_rating(post.rating, <i class="fa fa-star" aria-hidden="true"></i>, <i class="fa fa-star-half" aria-hidden="true"></i>) %> but it threw an error.

In short, I have a ruby method that takes a value from model (post.rating) and two icons (fa-star and fa-star-half). What is the best practice to use ruby method in conjunction with fontawesome's icons to achieve intended star rating?

I am aware there are several gems to do this, but I am trying to make it from scratch to help me understand rails more.

Upvotes: 0

Views: 690

Answers (1)

oleksandr
oleksandr

Reputation: 56

I really not sure if it's right way showing rating trough helper. But this should work:

create partial file

# _rating.html.erb
<%= fa_icon "#{icon_name}" %>

add to your required view file

# view.html.erb
<%= show_raiting(3.3) %>

and add method to helper, where path/to/your it's path to _rating.html.erb template

#***_helper.rb
def show_raiting(rating)
    rating = rating.to_f
    if rating.present?
      output_stars = ''
      rating.floor.times do
        output_stars += render partial: 'path/to/your/rating', locals: { icon_name: 'star' }
      end
      output_stars += render partial: 'path/to/your/rating', locals: { icon_name: 'star-half' } unless rating % 1 == 0
      output_stars.html_safe
    end
end

Upvotes: 1

Related Questions