Skip to content
This repository has been archived by the owner on Nov 12, 2019. It is now read-only.

Commit

Permalink
adding base api controller and routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Alejandra Jayme authored and Alejandra Jayme committed Nov 2, 2017
1 parent 41b239b commit 20c276f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
45 changes: 45 additions & 0 deletions app/controllers/api/v1/base_controller.rb
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
7 changes: 7 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@

match '/perf', to: 'perfs#create', via: :post

# api
namespace :api do
namespace :v1 do
resources :questions, only: [:show]
end
end

# The priority is based upon order of creation:
# first created -> highest priority.

Expand Down

0 comments on commit 20c276f

Please sign in to comment.