user2785628
user2785628

Reputation:

case statement dilemma ruby/rails helper method

I'm playing around with understanding case statements and using helpers in rails. I had this code in my view

<% case %>
  <%  when post.comments.count > 4 %>
    <%= image_tag "fresh.png", size: "28x28" %> 5+ comments
  <%  when post.comments.count > 2 %>
    <%= image_tag "rotten.jpeg", size: "31x31" %> 3+ comments
  <% else %>
<% end %>

its a funny piece of code that gives a user a picture of a fresh and or rotten tomato based on how many comments that person has on his or her post. Anyway I wanted to use a helper to case all this jumbled up code out of my view

I made a helper method

  def rotten_tomatoes(post)
    case
      when post.comments.count > 4
       image_tag "fresh.png", size: "28x28"
      when post.comments.count > 2
       image_tag "rotten.jpeg", size: "31x31"
      else
    end
  end

I want view to show the image_tag and also put out string that says 5+ comments or 3+ comments but when I put in this code

  def rotten_tomatoes(post)
    case
      when post.comments.count > 4
       image_tag "fresh.png", size: "28x28"
       "5+ comments"
      when post.comments.count > 2
       image_tag "rotten.jpeg", size: "31x31"
       "3+ comments"
      else
    end
  end

only the string prints out in the view and not the image tag sorry anyone know why?

I tried this

image_tag("fresh.png", size: "28x28")

which produced the same result

and

image_tag "fresh.png", size: "28x28",

which produced a syntax error

Upvotes: 0

Views: 413

Answers (1)

sawa
sawa

Reputation: 168209

[A]nyone know why?

Yes. In Ruby, the return value of a piece of code is the last evaluated part. For example, within the code chunk:

image_tag "fresh.png", size: "28x28"
"5+ comments"

the last evaluated part is:

"5+ comments"

That is why.

Upvotes: 1

Related Questions