This repository has been archived by the owner on Nov 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
adding base api controller and routes
- Loading branch information
Alejandra Jayme
authored and
Alejandra Jayme
committed
Nov 2, 2017
1 parent
41b239b
commit 20c276f
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
class Api::V1::BaseController < ApplicationController | ||
protect_from_forgery with: :null_session | ||
|
||
before_filter :destroy_session | ||
|
||
rescue_from ActiveRecord::RecordNotFound, with: :not_found! | ||
|
||
def destroy_session | ||
request.session_options[:skip] = true | ||
end | ||
|
||
def invalid_resource!(errors = []) | ||
api_error(status: 422, errors: errors) | ||
end | ||
|
||
def not_found! | ||
return api_error(status: 404, errors: 'Not found') | ||
end | ||
|
||
def api_error(status: 500, errors: []) | ||
unless Rails.env.production? | ||
puts errors.full_messages if errors.respond_to? :full_messages | ||
end | ||
head status: status and return if errors.empty? | ||
|
||
render json: jsonapi_format(errors).to_json, status: status | ||
end | ||
|
||
|
||
private | ||
|
||
def jsonapi_format(errors) | ||
return errors if errors.is_a? String | ||
errors_hash = {} | ||
errors.messages.each do |attribute, error| | ||
array_hash = [] | ||
error.each do |e| | ||
array_hash << {attribute: attribute, message: e} | ||
end | ||
errors_hash.merge!({ attribute => array_hash }) | ||
end | ||
|
||
return errors_hash | ||
end | ||
end |
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