Skip to content

Instantly share code, notes, and snippets.

@alg
Forked from anonymous/_form.html.erb
Created January 19, 2010 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alg/280670 to your computer and use it in GitHub Desktop.
Save alg/280670 to your computer and use it in GitHub Desktop.
class GlobalRESTController < ApplicationController
def index
@objects = model_class.all
respond_to do |format|
format.html
format.xml { render :xml => @objects }
end
end
def show
@object = model_class.find(params[:id])
respond_to do |format|
format.html
format.xml { render :xml => @object }
end
end
def new
@object = model_class.new
respond_to do |format|
format.html
format.xml { render :xml => @object }
end
end
def edit
@object = model_class.find(params[:id])
end
def create
@object = model_class.new(params[model_param_name])
respond_to do |format|
if @object.save
flash[:notice] = "#{model_class_name} was successfully created."
format.html { redirect_to(@object) }
format.xml { render :xml => @object, :status => :created, :location => @object }
else
format.html { render :action => "new" }
format.xml { render :xml => @object.errors, :status => :unprocessable_entity }
end
end
end
def update
@object = model_class.find(params[:id])
respond_to do |format|
if @object.update_attributes(params[model_param_name])
flash[:notice] = "#{model_class_name} was successfully updated."
format.html { redirect_to(@object) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @object.errors, :status => :unprocessable_entity }
end
end
end
def destroy
@object = model_class.find(params[:id])
@object.destroy
respond_to do |format|
format.html { redirect_to eval("#{params[:controller].underscore}_path") }
format.xml { head :ok }
end
end
private
# Gives the model class name. You can use it in your views, like "Add #{model_class_name}".
def model_class_name
@model_class_name ||= params[:controller].singularize.camelize
end
helper_method :model_class_name
# Returns the class of the model for CRUD operations.
def model_class
@model_class ||= model_class_name.constantize
end
# Returns the name of the model parameters hash in the POST parameters.
def model_param_name
@model_param_name ||= params[:controller].singularize.downcase
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment