Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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
share|improve this question

1 Answer 1

up vote 2 down vote accepted

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).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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