Easy Question: var on initialize for use by all methods

So I’m feeling a bit lazy right now, and I’m also struggling with making
my controller DRYer by moving some variables that are used by all
actions and views into an initilize method. Here’s the unDRY version:

def initialize

end

def index
@model_name = params[:section].classify.constantize
@section_name = params[:section]
@listings = @model_name.paginated_list(params[:page])
end

def detail
@model_name = params[:section].classify.constantize
@section_name = params[:section]
@listing = @model_name.find(params[:id])
end

And here’s my attempt, which does not work:

def initialize
@model_name = params[:section].classify.constantize
@section_name = params[:section]
end

def index
@listings = @model_name.paginated_list(params[:page])
end

def detail
@listing = @model_name.find(params[:id])
end

When I try this I get a 500 error which reads:

You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]

Is the params[] array not accessible by an initialize method?

Any help is appreciated.

don’t think it’s gonna work that way. You can do that using
before_filter

class ThingController < ApplicationController
before_filter :setup

def index
@listings = @model_name.paginated_list (params[:page])
end

def detail
@listing = @model_name.find(params[:id])
end

private
def setup
@model_name = params[:section].classify.constantiz
@section_name = params[:section]
end

end

there’s more at
http://railsmanual.org/module/ActionController::Filters::ClassMethods

On Feb 19, 2008 11:29 PM, Adam D. [email protected]