Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
Optimize IF clause with block in Rails

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

For readability reasons I would be very explicit:

<% if (calculated_value = product.value) %>
  <p class='...'><%= calculated_value %></p>
<& end %>
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!