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
-
def update
-
singular = params[:controller].singularize
-
camel = singular.camelize
-
klass = camel.constantize
-
@temp = klass.new params[singular]
-
@real = klass.find params[:id]
-
changes = object_diff(@real,@temp)
-
logger.info "Changes: #{changes.inspect}"
-
if changes.keys.size == 0
-
render :nothing => true, :status =>
k -
return
-
end
-
if @real.update_attributes(changes)
-
render :nothing => true, :status =>
k -
else
-
render :json => @real.errors.to_json, :status => 400
-
end
-
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.
-
if params[:format] != 'yaml'
-
@corporations = Corporation.find normal finder
-
end
-
respond_to do |format|
-
format.html
-
format.yaml { render :text => Corporation.find(:all, :select => 'id',
rder => 'id').to_yaml } -
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.


[...] 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