Created
November 15, 2012 16:20
-
-
Save meskallito/4079475 to your computer and use it in GitHub Desktop.
Api-Hal controller
This file contains hidden or 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
| class ApiController < ActionController::Metal | |
| include AbstractController::Callbacks | |
| include ActionController::Helpers | |
| include ActionController::Redirecting | |
| include ActionController::MimeResponds | |
| include ActionController::ForceSSL | |
| include ActionController::ParamsWrapper | |
| include ActionController::Instrumentation | |
| include ActionController::Rendering | |
| include ActionController::Renderers::All | |
| include ActionController::Rescue | |
| include ActionController::Serialization | |
| include Devise::Controllers::Helpers | |
| include Rails.application.routes.url_helpers | |
| prepend_before_filter :get_api_key | |
| before_filter :authenticate_user! | |
| rescue_from 'ActiveRecord::RecordNotFound' do | |
| respond_with ErrorMessage.instance(404, request) | |
| end | |
| private | |
| def get_api_key | |
| if api_key = params[:api_token].blank? && request.headers["Authorization"] | |
| params[:api_token] = api_key | |
| end | |
| end | |
| end | |
| class OrganizationsController < ApiController | |
| respond_to :hal | |
| def index | |
| respond_with organizations | |
| end | |
| def show | |
| respond_with organization | |
| end | |
| def create | |
| if organization.save | |
| respond_with organization | |
| else | |
| respond_with ErrorMessage.instance(422, request, messages: organization.errors ) | |
| end | |
| end | |
| def update | |
| if organization.update_attributes(params.permit(:code, :name)) | |
| respond_with organization | |
| else | |
| respond_with ErrorMessage.instance(422, request, messages: organization.errors ) | |
| end | |
| end | |
| def destroy | |
| organization.destroy | |
| respond_with organization | |
| end | |
| private | |
| def organization | |
| @organization ||= if params[:action] =~ /new|create/ | |
| Organization.new(params.permit(:code, :name)) | |
| else | |
| Organization.find(params[:id]) | |
| end | |
| end | |
| def organizations | |
| @organizations = Organization.all | |
| end | |
| def default_serializer_options | |
| { hypermedia_provider: { | |
| array: Hypermedia.new.tap { |h| h.add_link :self, organizations_path }, | |
| object: Hypermedia.new.tap { |h| h.add_link :self, organization_path("{id}") } | |
| } | |
| } | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment