views:

27

answers:

3

I'm developing a classified ads site which will have display same sidebar on almost every page. A list of categories which are fetched from the database.

I find myself duplicating the same code in each controller to do this. i.e.

before_filter :load_categories

Where :load_categories performs a simple

private

def load_categories
  @categories = Category.all
end

Not very dry when you have a lot of controllers.

Is there a way for my to dry this process up?

A: 

You can put def load_categories definition in ApplicationController and it will be accessible from every controller in your application.
You can put before_filter :load_categories in ApplicationController too, if you want it to be executed for every controller.

Although, frankly, it doesn't seem like a huge case of code redundancy to me. In fact, simply calling Category.all in every action/view where you need categories might be simpler. Since results are cached, there's no performance penalty.

Nikita Rybak
A: 

You can put your method in ApplicationController and your before_filter in too.

If you want avoid it in one specific controller you can skip it after

shingara
+3  A: 

You could put this on ApplicationController, but honestly I recommend against that. ApplicationController tends to become a big bloated blob over time, accumulating utility functions that are really not related, definitely not SRP. It can get ugly.

What I've done to keep things DRY is to create a parent controller that related controllers can inherit from. Put your before_filter on that and have the related category-using controllers inherit from it.

Maybe:

class MainPagesController < ApplicationController
  before_filter :load_categories

  private

  def load_categories
    @categories = Category.all
  end
end

class SomeController < MainPagesController
  # etc.
end

If your app is small-ish, won't grow significantly over time, and you truly do load @categories on almost all of your pages, then putting it on ApplicationController might make sense. But I tend to err on the side of over-DRYing my code. Very small classes that have siloed functionality is never a bad thing.

Dave Sims