Created
October 26, 2014 18:26
-
-
Save RyanDawkins/d27f10596b518b89a104 to your computer and use it in GitHub Desktop.
Generic Ruby REST controller for rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
render json: mything.directly
()
usage is inconsistent. Looking at 29I 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.