Skip to content

Instantly share code, notes, and snippets.

@RyanDawkins
Created October 26, 2014 18:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanDawkins/d27f10596b518b89a104 to your computer and use it in GitHub Desktop.
Save RyanDawkins/d27f10596b518b89a104 to your computer and use it in GitHub Desktop.
Generic Ruby REST controller for rails
class RestController < ApplicationController
before_filter :find, :only => [:show, :update, :delete]
def index
@objects = get_class().all
render json: @objects
end
def show
if @object
render json: @object
else
render json: error_message("Couldn't find your #{get_class}")
end
end
def create
@object = get_class.new from_params
if @object.save
render json: @object
else
render json: error_message("Didn't send the correct params")
end
end
def update
if @object and (@object.update from_params) and @object.save
render json: @object
else
render json: error_message("We had a problem saving your #{get_class}")
end
end
def delete
if @object
render json: @object.destroy
else
render json: error_message("We had a problem finding your customer")
end
end
def find
if params[:id]
begin
@object = get_class.find(params[:id])
rescue
@object = nil
end
end
end
def error_message message
{
message: message
}
end
end
@sb8244
Copy link

sb8244 commented Oct 27, 2014

  • Have you seen respond_with? Responders really clean up this type of code
  • rescue without a specific error is super super dangerous
  • why put things in @object to just render json? I would just do render json: mything.directly
  • Mix of () usage is inconsistent. Looking at 29

I understand this is an attempt at abstraction, but I think it might actually cause more harm than good because you will need to go against the grain in most systems.

@nakhli
Copy link

nakhli commented Nov 12, 2014

I am probably missing sthing but where is from_params defined?

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