Search code examples
ruby-on-railshelperpartial

Rails 4: How to render a method with multiple returns


A method with multiple returns

def savings_for(id)
    payments = Payment.user_of(id).all
    savings = 0
    num = 0
    payments.each do |payment|
    item = Item.find(payment.id)
        num = num+1
        savings += item.price
    end
    return savings, num
end

I´m using this helper in a view. Like this

<p>You´ve save <b><%=savings_for(current_user)%>$</b></p>

But I don´t know how render correctly:

You´ve save  [#<BigDecimal:108289ca0,'0.13E3',9(27)>, 3]$

Update: Changed the return method:

return "<b>#{savings}€</b> en #{num}"

How i can render the html bold tag?


Solution

  • So, a helper method that is supposed to return something to render on a page, should return a string, not an array of multiple values.

    You should decide yourself how you want the multiple values to display. How do you want them to display? Maybe just separated by a comma? Okay, so format it like that yourself inside the helper method:

      ...
      return "#{savings}, #{num}"
    end
    

    updated answer for updated question

    Update: Changed the return method:

    return "<b>#{savings}€</b> en #{num}"
    

    How i can render the html bold tag?

    I'd do this:

     def render_savings_for(savings, num)
        safe_join(
           content_tag("b", "#{savings}€"),
           " en ",
           num
        )
     end
    

    Writing your own html-rendering helpers can look a bit confusing, but there are really just a few simple concepts around html safety to understand. I've previously tried to explain some of them here: https://bibwild.wordpress.com/2013/12/19/you-never-want-to-call-html_safe-in-a-rails-template/

    Another alternative would be using a view partial instead of a helper method, which wouldn't require you to pay attention to html_safety tricks it would just take care of it for you, but for something this simple I think a helper method is simpler.

    Next, you're going to start asking about i18n... make a new question! :)