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”
Sorry, comments are closed for this article.
July 6th, 2006 at 12:20 AM 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.
July 6th, 2006 at 03:36 PM 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
July 8th, 2006 at 04:10 AM Thanks for the post Ryan! Unfortunately, now I am racking my brain on going back and revisiting a lot of code! --Tom
July 22nd, 2006 at 03:54 PM 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