Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda