I’m no expert on REST-ful development. But after seeing David’s presentation on ActiveResource, MLY’s article on HABTM, and after looking at Molecule I was inspired to refactor some of my controllers a bit. When I was done, I managed to squeeze the CRUD (Create, Read, Update, Delete) part of my controllers down from around 50-75 lines per controller to around 20-30 lines.


class ApplicationController < ActionController::Base
  ...

  private

  def save_or_update(obj,params=nil)
    begin
      ((params and !obj.new_record?) ? obj.update_attributes(params) : obj.save) or raise errors_for obj
      flash_notice "#{obj.class} saved successfully", :good, :now
      redirect_to :action => "show", :permalink =>obj.permalink
    rescue Exception => e
      flash_notice "There was an error saving the #{obj.class.downcase} #{e}", :bad, :now
    end
  end

  def errors_for(obj)
    "<ul>#{obj.errors.full_messages.collect{|e| "<li>#{e}</li>"}}</ul>" if obj and obj.errors
  end

  def flash_notice(message,status=:good,now=false)
    now ? (flash.now[:notice], flash.now[:class] = message, status) : (flash[:notice], flash[:class] = message, status)
  end

end

class PageController < ApplicationController
  ...

  def show
    @page = get_page
  end

  def new
    @page = Page.new(params[:page])
    save_or_update(@page) if request.post? 
  end

  def edit
    @page = get_page
    save_or_update(@page,params[:page]) if request.post? 
  end

  private

  def get_page(permalink=params[:permalink])
    Page.find_by_permalink(permalink)
  end

end

4 Responses to “REST-ful DRY Technique: Make your Controllers Even Smaller”

  1. Ryan Says:
    I should probably clarify that this code snippit doesn't _really_ have anything to do with "REST":http://en.wikipedia.org/wiki/REST. But it does set up your controllers in a way that makes it easier to comply with REST.
  2. peter Says:
    Ryan, thanks for this blog post. These well chosen snips of code came to me at the perfect time for a new project. I like how you move the bulk of the code to the application controller. I think that Rails scaffolding does not get people thinking along the lines of using the class inheritance enough. Peter
  3. Tom Rossi Says:
    Thanks for the post Ryan! Unfortunately, now I am racking my brain on going back and revisiting a lot of code! --Tom
  4. peter Says:
    In the last few weeks I tried this approach but became concerned that I was repeating even the 20-30 lines remaining in the controllers. Then I found this link http://cleanair.highgroove.com/articles/2006/06/27/metaprogramming-and-ruby-on-rails

Sorry, comments are closed for this article.