CrudVision – Lisa Seelye

July 25, 2007

What’s better than CRUD?

Filed under: api,evedb.info,rails,snippet — Lisa Seelye @ 07:50

DRY CRUD!

That is, of course, "Don't repeat yourself".

With my evedb.info site I have to essentially rsync two databases whilst mangling schema. The process will take FOREVER (Mainly because I'm not multithreading this process) but it's automated.

I kept having to write CRUD methods in all of my controllers to deal with updating evedb.info as I talked about in this linked post and they were ALL the same. So being the lazy programmer I am I put them all in the ApplicationController:

Here's the update method

RUBY:
  1. def update
  2.     singular = params[:controller].singularize
  3.     camel = singular.camelize
  4.     klass = camel.constantize
  5.     @temp = klass.new params[singular]
  6.     @real = klass.find params[:id]
  7.     changes = object_diff(@real,@temp)
  8.     logger.info "Changes: #{changes.inspect}"
  9.     if changes.keys.size == 0
  10.       render :nothing => true, :status => :o k
  11.       return
  12.     end
  13.     if @real.update_attributes(changes)
  14.       render :nothing => true, :status => :o k
  15.     else
  16.       render :json => @real.errors.to_json, :status => 400
  17.     end
  18.   end

By abusing Rails's constantize I can mangle the controller's name ("corporations") into the model it's handling: Corporation and treat it klass as if it was actually spelled Corporation. Personally I think that is very cool.

object_diff is a method I wrote to find the differences between two ActiveRecord::Base derrived objects. Loop through attributes hash and note things that change. changes is those attributes that have changed.

The only part I haven't been able to DRY out is the index method which always returns YAML for my scripts but only the IDs of the objects.

RUBY:
  1. if params[:format] != 'yaml'
  2.   @corporations = Corporation.find normal finder
  3. end
  4. respond_to do |format|
  5.   format.html
  6.   format.yaml { render :text => Corporation.find(:all, :select => 'id', :o rder => 'id').to_yaml }
  7. end

But I don't think I can DRY it out becase Corporation YAML finder actually selects another column that my script uses. Oh well.

1 Comment »

  1. [...] That’s nice. A google search reveals that quite a lot of people write code like [...]

    Pingback by Little Impact » Blog Archive » Constantize with Care — August 13, 2008 @ 23:00

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress