Home > Back-end >  Optimize IF clause with block in Rails
Optimize IF clause with block in Rails

Time:10-20

I have something like:

<%= "<p class='...'>#{product.value}</p>".html_safe if product.value %>

So I want to show the value wrapped in some html if it exists. Problem is that value is a method that requires some calculations and the way above for every product value is calculated two times which doubles my page loading time.

Any way to optimize this?

CodePudding user response:

I think the following should work:

<%= product.value.then { |v| content_tag(:p, v, class: '...') if v } %>

The value method is only called once on the product object. After that, it is passed to a block then that will define what is the result of the overall expression. Without calling again the value method, inside the block we determine what is the value that should be returned (if any).

Note: The generation of the HTML object has been replaced by an invocation of the content_tag helper method.

  • Related