2
\$\begingroup\$

I have this messy helper method:

def gesture(klass, item, text, desc)
  element_class = klass.to_s + " gesture"
  content_tag :li do
    if klass == :sell  
      link_to new_reply_path(item_id: item.id), title: desc, data: {qtip: desc}, class: element_class do
        content_tag(:div, nil, class: element_class) +
        content_tag(:span, text, class: 'gesture-text')
      end
    elsif klass == :alternative
      link_to new_reply_path(item_id: item.id, alternative: true), title: desc, data: {qtip: desc}, class: element_class do
        content_tag(:div, nil, class: element_class) +
        content_tag(:span, text, class: 'gesture-text')
      end
    elsif klass == :join
      link_to new_item_affiliation_path(item), title: desc, data: {qtip: desc}, class: element_class do
        content_tag(:div, nil, class: element_class) +
        content_tag(:span, text, class: 'gesture-text')
      end
    end  
  end 
end

As you can see, it has a lot of repetition, any idea on how I can refactor it?

\$\endgroup\$
1
\$\begingroup\$

I'd write:

def gesture(klass, item, text, desc)
  element_class = [klass.to_s, "gesture"]
  url = case klass
  when :sell
    new_reply_path(item_id: item.id)
  when :alternative
    new_reply_path(item_id: item.id, alternative: true)
  when :join
    new_item_affiliation_path(item)
  else
    fail("Unsupported klass: #{klass}")
  end

  content_tag(:li) do
    link_to(url, title: desc, data: {qtip: desc}, class: element_class) do
      content_tag(:div, nil, class: element_class) +
        content_tag(:span, text, class: 'gesture-text')
    end    
  end 
end
\$\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.