# Easy Question: var on initialize for use by all methods

**URL:** <https://www.ruby-forum.com/t/easy-question-var-on-initialize-for-use-by-all-methods/129612>\
**Category:** Rails\
**Created:** [February 20, 2008, 2:29am UTC](https://www.ruby-forum.com/t/easy-question-var-on-initialize-for-use-by-all-methods/129612 "2008-02-20T02:29:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![adamdorsey](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ed8c4c/32.png) [@adamdorsey](https://www.ruby-forum.com/u/adamdorsey)\
**Post date:** [February 20, 2008, 2:29am UTC](https://www.ruby-forum.com/t/easy-question-var-on-initialize-for-use-by-all-methods/129612/1 "2008-02-20T02:29:29Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![adamdorsey](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/ed8c4c/32.png) [@adamdorsey](https://www.ruby-forum.com/u/adamdorsey)\
**Post date:** [February 20, 2008, 4:33am UTC](https://www.ruby-forum.com/t/easy-question-var-on-initialize-for-use-by-all-methods/129612/2 "2008-02-20T04:33:30Z")

</div>

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](http://railsmanual.org/module/ActionController::Filters::ClassMethods)

On Feb 19, 2008 11:29 PM, Adam D. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
