2
\$\begingroup\$

How to get rid of that duplicaiton in if conditional?

def set_caption(result)
  if result.respond_to?(:app_name)
    content_tag(:div, result.type_name, class: 'type-name') + 
      content_tag(:div, result.app_name, class: 'app-name')
  else
    content_tag(:div, result.type_name, class: 'type-name')
  end
end
\$\endgroup\$
2
\$\begingroup\$

Just use variables for repeated expressions:

def set_caption(result)
  type_div = content_tag(:div, result.type_name, class: 'type-name') 
  if result.respond_to?(:app_name)
    type_div + content_tag(:div, result.app_name, class: 'app-name')
  else
    type_div
  end
end

Note that you can move the conditional further in: type_div + (condition ? app_div : ""). Use this style whenever this adds readibility (here I'd say it doesn't).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.