Taro, if you;re talking about the very common functions for basic CRUD
operations on tables then yes, I think there are a few strategies to
keep DRY. I can see by reading around that the RESTful approach has
some pretty clear guidelines to help with this but I'm not there yet.
What I have found extremely helpful is a strategy of defining a parent
class from which I inherit for my classes (controllers) that do
concrete work.
So, lets call this controller Crud
class Crud < ActionController::base
bunch of stuff we'll discuss below
end
and then my real controllers are
class Concrete < Crud
end
Now in the Crud controller I define some methods, specifically in my
case "show", "new", "edit" and "delete" (you can collapse these even
further if you wanted but for me this has been a reasonable balance
between being succint and being clear.
The next part is to take advantage of Rails consistency in naming. So
for a given controller we can deduce the model name. We know it will
have an id field as primary key and if we manage our routes
consistently then we know our parameters will be consistent. Then if
we agree to use a standard instance variable name for our form data we
can abstract the entire CRUD process. In my example, @row is what we
agree to always be the variable that holds data from the database.
Here's an example for the "show" method:
def show
if !@row = crud_obj.find((params[:name]) then
redirect_to home_url
return
end
article_render_show
end
crud_obj is the model object related to our controller. It is defined
as below.
def crud_obj
return Object.const_get(class_name)
end
def class_name
return self.class.name.sub(/Controller/,"")
end
Once you have a way to abstract the name of the model class from the
controller class, you can pretty much abstract the entire crud
process.
I now have several controllers than have absolutely no code in them
whatsoever - they just inherit the methods from this parent class. To
create a new class I simply:
1. Create a new class derived from Crud
2. Create the views "show" and "edit"
3. The logic will use "edit" for new and update functions, and "show"
for the rest. You could easily decide to use only one view but I find
they're often different enough to warrant clear separation.
If you then create a customer form builder you can get a lot of basic
functionality built reliably very fast.
Cheers, --Kip