top | item 80941

(no title)

HiddenBek | 18 years ago

Rails has filters that can run before, after, or around some or all of your controller actions. This can be done on a per controller basis, or it can be application wide. In this case you'd probably define a "load_widgets" before_filter in your application controller, then set your view to display whichever widgets it had data for.

discuss

order

qaexl|18 years ago

There are other pieces of this puzzle besides before_filter.

In Rails, you don't necessarily have to have a monolithic view. On more complex sites, you use fragments, called partials. Sidebars can be easily created by having a "shared" view directory full of partials. Further, there is a content_for helper in Rails views. Views render late; you can set an instance variable in the subviews that will affect what gets rendered in the layout. Trying to keep track of that can get hairy, so content_for abstracts that for you. Combined with the partials and the before_filter in the controllers, you can get a view to produce a number of things without having to resort to pulling DB info inside the views -- that reminds me too much of the bad old days of PHP.

In the logged-in users example, in what is normally in the sidebar, you use a render :partial => 'shared/users' if @users; then add a before_filter in the site-wide application layout to pull in the data if someone is logged in. A more complicated example is to render a "sidebar" partial, which renders more partials depending on some array of sidebars you want to display ... then use a before_filter to figure out what you want to populate the sidebars with. Any controller or actions can override or add to that sidebar array.

The main thing that sucks about this kind of organization is having the code scattered in a number of different files. This is where using an editor that knows the relationship between the files is important -- you can hit some key combination and jump between the different fragments without having to hunt them down in the file browser.

myoung8|18 years ago

I think having that degree of modularity is a great thing (granted you have a good text editor). It makes it much easier to understand what's happening in the code and much easier to maintain it (and get someone new up to speed).

I was helping out on this one site built in PHP a while back where the code wasn't organized this way. It took me about a week to figure out where things were, which was a huge productivity drag for the other guys.

mrtron|18 years ago

Similarly, Django has context processors for the same purpose.