Ever noticed how all CRUD methods on each controller starts with the same line:
@item = Model.find(params[:id]) ?
Hey! why not use filter so we don’t repeat ourselves ?
class PostsController < ApplicationController before_filter :find_post, :only => [:show, :edit, :update, :destroy] def index @posts = Post.find(:all) end def show end def new @post = Post.new end def edit end def create @post = Post.new(params[:post]) if @post.save flash[:notice] = 'Post was successfully created.' redirect_to post_url(@post) else render :action => "new" end end def update if @post.update_attributes(params[:post]) flash[:notice] = 'Post was successfully updated.' redirect_to post_url(@post) else render :action => "edit" end end def destroy @post.destroy redirect_to posts_url end private def find_post @post = Post.find(params[:id]) end end
The cool thing about this is, if you decide to switch to using model name in the url, you’ll only have one line to change!
It’s a small step for Rails, but a great step towards honouring the DRY principle:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
– The Programatic Programmer
DRY-fulness we salute you!Advertisements