What's the best way to stop repeating this line in my contro

Hi,

I am trying to follow the “DRY” principle and came across a problem.
I am working on a small ajax task manager, and right now in the index
page which renders the list, I have (for example, in the Lists
controller):

def index
@lists = List.find(:all)
end

Now within the controller there’s also a list_add action which is
called via ajax…

def list_add
if List.create(params[:list])
@lists = List.find(:all)
render(:partial => “listform”)
end
end

I need to put the @lists = List.find(:all) in it again so it gets the
new updated list to render via AJAX like I did in the index action,
and I have to do this for every action I need…

Is there a way to do this so I can stop repeating myself? Or am I
outta luck?

Thanks.

use a :before_filter

at top of your controller:

before_filter :get_list

then add:

private
def get_list
@lists = List.find(:all)
end

now get_list will be called before index, list_add, or any other
controller
methods. If you just want it for those two change the top line to:

before_filter :get_list, :only => [:index, :list_add]

you can also use :except => [ … ]