On 9/24/06, Chris T [email protected] wrote:
I can improve things using your code about (though have to singularize
the names, as the controller names are plural versions of the model
names). I’d got a simple model_name method defined in each subcontroller
to define the model name, but you’re right, I could DRY it up further
and just infer this from the controller name in the MasterController.
I’ve been playing with what I think is some really fun stuff in that
vein for some weeks now. I have most of it bundled in a plugin called
resourcey_utils which you can find here:
http://sethrasmussen.com/svn/rails/plugins
There are some handy before_filters you can use with these same
assumptions we’re discussing to prepare a new resource instance, or
collection, etc. They are pretty generic, but like I say, fun and onto
something, methinks. I’m sure I’ll enhance it as time goes on. Using
these conventions, I’ve whittled a resource crud controller down to
something like this:
class BlogPostTypesController < ApplicationController
before_filter :new_resource, :only => %w(new create)
before_filter :find_resource, :only => %w(edit update destroy)
before_filter :paginate_resource, :only => :index
def create
if create_resource
redirect_back_or_default(blog_post_types_url)
else
render :action => :new
end
end
def edit
render :action => ‘new’
end
def update
if update_resource
redirect_back_or_default(blog_post_types_url)
else
render :action => ‘edit’
end
end
def delete
destroy_resource
redirect_back_or_default(blog_post_types_url)
end
end
If your controller could stay that generic, you could even abstract all
of those remaining methods into one or two class level calls or perhaps
something that is defined dynamically. I’ll probably work on adding
that, even if just for fun, in the near future.
I am thinking about
creating some class methods to wrap before filters that create and fine
a resource for the appropriate cruddy actions, too, though this is
another case where standardizing a slightly less assuming approach
might be good.
All in all, making certain assumptions when you can definitely kicks
ass and makes for clean code that feels like a warm hug to read.