Drying up my controllers using inheritance

Morning

I have three controllers, which share a lot of functionality. I was
wonder if there was a way to keep dry using a base controller and then
inherit from it in my other controllers.

Here some code from one of my controllers

def show
@home = Home.find(params[:id])
if @home.active?
render :action => ‘show_active_true’
else
render :action => ‘show_active_false’
end
rescue ActiveRecord::RecordNotFound
logger.error(“An attempt has been made to access a home that does not
exist in the database. The home id was #{params[:id]}”)
flash_failure ‘An attempt has been made to access a home that does
not exist in the database.’
redirect_to :action => ‘index’
end

The show method in the other controllers are basically the same except,
they will relate to another model. So you have @care_agency =
CareAgency.find(params[:id]). Basically, I just want to replace the
word home with care_agency in that particular controller.

Is there a nice dry way to abstract and just basically change the model?

Thanks for any pointers!
Harvey

On 9/18/06, harvey [email protected] wrote:

Morning

The show method in the other controllers are basically the same except,
they will relate to another model. So you have @care_agency =
CareAgency.find(params[:id]). Basically, I just want to replace the
word home with care_agency in that particular controller.

Is there a nice dry way to abstract and just basically change the model?

Maybe this might work for you:

class BaseController < ActionController::Base

def BaseController.model(model_name)
@model_class = const_get(Inflector.classify(model_name))
@model_var = model_name
end

def show
inst_var=“@#{model_var}”, model_class.find(params[:id]
instance_variable_set(inst_var)
if inst_var.active?
render :action => ‘show_active_true’
else
render :action => ‘show_active_false’
end
rescue ActiveRecord::RecordNotFound
logger.error(“An attempt has been made to access a
#{model_class.name} that does not
exist in the database. The #{model_class.name} id was #{params[:id]}”)
flash_failure ‘An attempt has been made to access a
#{model_class.name} that does
not exist in the database.’
redirect_to :action => ‘index’
end

end

And:

class HomeController < BaseController
model :home
end

Cheers,
Max

Harvey,

If there’s a lot of duplication among your controllers and other
objects, consider consolidating the data itself. For example, “home” and
“care_agency” look like two permutations of the same entity - maybe a
“facility” table with a column for facility_type would be a simpler way
to go.

Shauna

Or you could do the same thing by mixing in a module. That seems a
little more Ruby-like to me.

Guys
Thanks for all the help.
Harvey