Created
April 9, 2014 13:42
-
-
Save mrcljx/10271999 to your computer and use it in GitHub Desktop.
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
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