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

Mampf api #137

Merged
merged 3 commits into from
Nov 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 app/controllers/api/v1/questions_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class Api::V1::QuestionsController < Api::V1::BaseController
def show
@qs = Question.includes(:answers).find(params[:id])

render json: @qs.as_json(:only => [:text], include: { answers: {:only => [:text, :correct]}})
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