Skip to content

Instantly share code, notes, and snippets.

@mrcljx
Created April 9, 2014 13:42
Show Gist options
  • Save mrcljx/10271999 to your computer and use it in GitHub Desktop.
Save mrcljx/10271999 to your computer and use it in GitHub Desktop.
module ResourcesController
extend ActiveSupport::Concern
def index
render json: resources
end
def show
render json: resource
end
def create
if update_resource
render json: resource
else
render json: resource.errors, status: 422
end
end
def update
if update_resource
render json: resource
else
render json: resource.errors, status: 422
end
end
def destroy
if soft_deletable?
resource.deleted_at = Time.now
resource.save
render json: { id: resource.id }
else
render json: { id: resource.id }, status: :forbidden
end
end
protected
def update_resource
resource.save
end
def resource_class
self.class.resource_class
end
def resources
if soft_deletable?
resources_with_deleted.where(deleted_at: nil)
else
resources_with_deleted
end
end
def resources_with_deleted
resource_class
end
def resource
@resource ||= begin
if id = params[:id]
resources.find(id) or raise MongoMapper::DocumentNotFound
else
build_resource
end
end
end
def build_resource
resources.new
end
def soft_deletable?
false
end
module ClassMethods
def resource_class
@resource_class ||= name.sub(/Controller$/, '').tableize.singularize.classify.demodulize.constantize
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment