Topic: Refactoring similar RJS templates

I can't seem to find a way to refactor my RJS templates.

I have the typical drill-down structures (for toys): The "Age" column contains "Baby", "Toddler", "Elementary", "Pre-Teen"...; click on "Toddler" and the adjoining column contains "Active", "Developmental", "Learning"...; when you first bring up the page, initially "Baby" (first element of level 1) and "Crib" (first element of level 2) are selected, and the adjoining column contains a picture and description of the featured toy.

My level2.js.rjs file contains

page.replace_html("listLevel2", :partial => "level2", :collection => @level2)
page.replace_html("picAndDescHeader", @level2[0].name)
page.replace_html("picAndDescDescr", @level2[0].description)

and is invoked 1) in a render from the toys.html.erb, and 2) in an AJAX call clicking on any of the elements from level 1.

My picAndDesc.js.rjs file contains

page.replace_html("picAndDescHeader", @featured_product.name)
page.replace_html("picAndDescDescr", @featured_product.description)

which is invoked 1) in a render from the toys.html.erb, selecting the initial toy, or 2) in an AJAX call clicking on any of the elements from level2.

What I think I should be able to do is replace level2.js.rjs with something like

page.replace_html("listLevel2", :partial => "level2", :collection => @level2)
call picAndDesc.js.rjs (@level2[0]) # not real code

But, of course, I can't.

Does anyone have any suggestions?

Re: Refactoring similar RJS templates

I think your primary goal is to eleminate the duplicate code from your 2 rjs files. So I even have two suggestions:

1.) Remove line 2 and 3 from level2.js.rjs. Then, whenever you call level2.js.rjs, set @featured_product and call picAndDesc.js.rjs afterwards.

2.) Use only one rjs file:

name        = @featured_product ? @featured_product.name        : @level2[0].name
description = @featured_product ? @featured_product.description : @level2[0].description

if !@level2.nil?
  page.replace_html( "listLevel2", :partial => "level2", :collection => @level2 )
end

page.replace_html( "picAndDescHeader", name )
page.replace_html( "picAndDescDescr",  description )


This example assumes, that @level2 was nil when your old picAndDesc.js.rjs was called. It also assumes, that @featured_product was nil, when your old level2.js.rjs was called.

It's the nature of a forum to contain lots of information. That is because old threads don't get deleted:
Tutorials: http://railsforum.com/viewforum.php?id=20
Extremely Powerful Tool: http://railsforum.com/search.php

Re: Refactoring similar RJS templates

CooL!! Big thanks for info.