Ammar
Ammar

Reputation: 1091

Need Help DRYing things up - Rails 3.1

.row
    .nine.columns.centered
        %ul.bucketlist

            - @buckets.each_with_index do |resource, index|
                %a{:href => "#{bucket_path(resource)}"}
                    %li.bucket
                        %h4= index + 1
                        %h5= resouce.name

            %a{:href => "#{new_bucket_path}"}
                %li.bucket.empty
                    = image_tag "add.gif"
                    %h5 Add Bucket

I have the above code written in 3 different views, with only minor differences between them. This doesn't seem very DRY to me, so I'm looking for some help to clean this up.

Between the views only a few things vary:

  1. @buckets.each - The @buckets collection needs to change between @notes, @units aswell.
  2. #{bucket_path} - I'd like to be able to pass in a variable so that bucket_path becomes resource_path.

If anyone can offer any help, it'd be much appreciated.

Upvotes: 0

Views: 80

Answers (2)

harald
harald

Reputation: 6126

My experience with haml is limited, but I think you should be able to put the common code into a partial (a file named _common.html.haml, for instance), and then in the view simply do:

= render 'common', :items => @buckets, :new_item_path => new_bucket_path

Then change the partial like this:

%ul.bucketlist
    - items.each_with_index do |resource, index|
        %a{:href => url_for(resource)}
            %li.bucket
                %h4= index + 1
                %h5= resouce.name

    %a{:href => "#{new_item_path}"}
        %li.bucket.empty
            = image_tag "add.gif"
            %h5 Add Item

Upvotes: 2

Ibrahim Muhammad
Ibrahim Muhammad

Reputation: 2896

  • One solution could be writing a helper function to generate the html. People typically don't like html in helpers, but in this case it would be a good idea. Write a function where you pass in the resource name and it generates this code for you

  • Another way is to check the controller you are in and generate the required code based on that. For instance

    resource = @buckets if params[controller]=='bucket'

    A more condensed way to remove if statements would be something like following, but i havnt tried it out.

    exec "resource = @#{params[:controller]}s"

Let me know if you need more help.

Upvotes: 0

Related Questions