2
\$\begingroup\$

I've got this code in my View that just list two type of links.

Here's an example output:

Nounal Pages

  • cleaners/house-cleaners

Verbal Pages

  • cleaning/house-cleaning

Here's the view code. How could this be refactored to remove duplicate and push logic and loops out of the view?

  %h3 Nounal Pages
  %ul.row-fluid
  - categories.each do |category|
    - subcategories.each do |subcategory|
      %ul
        %li= link_to "#{category.pluralised_nounal_slug}/#{subcategory.pluralised_nounal_slug}", main_app.new_pluralised_nounal_subcategory_path(category: category.pluralised_nounal_slug, subcategory: subcategory.pluralised_nounal_slug), target: '_blank'

  %h3 Verbal Pages
  %ul
  - categories.each do |category|
    - subcategories.each do |subcategory|
      - if category.verbal_slug.present? && subcategory.verbal_slug.present?
        %ul
          %li= link_to "#{category.verbal_slug}/#{subcategory.verbal_slug}", main_app.new_verbal_subcategory_path(category: category.verbal_slug, subcategory: subcategory.verbal_slug, aspect: 'verbal'), target: '_blank'
\$\endgroup\$
2
\$\begingroup\$

You might consider having the controller (or some other thing that is not the view) set up all of the data, such that the view can merely do this:

- @nounals.each do |text, uri|
  %ul
    %li= link_to text, uri, target: '_blank'

and

- @verbals.each do |text, uri|
  %ul
    %li= link_to text, uri, target: '_blank'

Once the two loops are the same other than the variable, you can use a partial template to render each of them.

\$\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.