Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.