Skip to content

Instantly share code, notes, and snippets.

@lorenjohnson
Created August 26, 2011 07:06
Show Gist options
  • Save lorenjohnson/1172867 to your computer and use it in GitHub Desktop.
Save lorenjohnson/1172867 to your computer and use it in GitHub Desktop.
Meta Programming all the SetupControllers
class SetupController < ApplicationController
before_filter :set_instance_and_user, :object, :objects
respond_to :html, :js
def index
flash[:warning] = flash[:notice] = nil if !params[:cancel].blank?
eval("@#{controller.controller_name.singularize} = #{controller.controller_name}")
instance_variable_set("@#{object_name}", model_klass.new(params[object_name]))
instance_variable_set("@#{objects_name}", model_klass.order("updated_on DESC"))
respond_with(eval("@#{objects_name}"))
end
# ... remaining actions to follow suit...
# this is in essence exactly the sort of thing that the resource_controller and make_resourceful gems
# do, which I used in every project until Rails 3.
# Rails 3 has this added controller helper called respond_with (and it's corresponding class level call
# of respond_to -- see above).
# This effectively shortens the controller code enough that there is some wisdom in not merging them
# into one via meta-programming as I'm doing here. I'm still on the fence as to whether
# we should go this route, yet. It's a matter of timing. I'd like to see the Setup (what I was calling Config)
# areas settle a little longer before extrapolating them into a single pattern...
# Mostly because it takes an investment of time to do that well, test it and iron out any edge cases,
# in addition once you're working from a meta-programmed controller there is an added level to the debug
# of things which sometimes causes more trouble than it was worth.
protected
def object_name
controller.controller_name.singularize
end
def objects_name
controller.controller_name
end
def model_klass
eval(controller.controller_name.singularize.camelize)
end
def model_klass_name
controller_name.singularize.underscore
end
def object
eval("@#{object_name}")
end
def objects
eval("@#{objects_name}")
end
def set_instance_and_user
case action_name.to_sym
when :show, :edit, :update, :destroy
instance_variable_set("@#{model_klass_name}", model_klass.find(params[:id]))
when :create, :new
instance_variable_set("@#{model_klass_name}", model_klass.new(params[model_klass_name]))
end
eval("@#{model_klass_name}.current_user = current_user")
end
end
@lorenjohnson
Copy link
Author

Do note that this is a very rough ("gist" in fact), this is not functioning or complete code... Don't let it confuse you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment