1 class ApplicationController < ActionController::Base
3 before_filter :uncamelcase_params_hash_keys
4 before_filter :find_object_by_uuid, :except => :index
6 unless Rails.application.config.consider_all_requests_local
9 rescue_from ActiveRecord::RecordNotFound,
10 :with => :render_not_found
11 rescue_from ActionController::RoutingError,
12 :with => :render_not_found
13 rescue_from ActionController::UnknownController,
14 :with => :render_not_found
15 rescue_from ActionController::UnknownAction,
16 :with => :render_not_found
20 logger.error e.inspect
21 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
22 if @object and @object.errors and @object.errors.full_messages
23 errors = @object.errors.full_messages
27 render json: { errors: errors }, status: 422
30 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
31 logger.error e.inspect
32 render json: { errors: ["Path not found"] }, status: 404
36 @objects ||= model_class.all
42 render json: @object.as_api_response(:superuser)
44 render_not_found("object not found")
49 @attrs = params[resource_name]
51 raise "no #{resource_name} (or #{resource_name.camelcase(:lower)}) provided with request #{params.inspect}"
53 if @attrs.class == String
54 @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
56 @object = model_class.new @attrs
62 @attrs = params[resource_name]
63 if @attrs.is_a? String
64 @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
66 @object.update_attributes @attrs
73 controller_name.classify.constantize
76 def resource_name # params[] key used by client
77 controller_name.singularize
80 def find_object_by_uuid
81 if params[:id] and params[:id].match /\D/
82 params[:uuid] = params.delete :id
84 @object = model_class.where('uuid=?', params[:uuid]).first
87 def self.accept_attribute_as_json(attr, force_class=nil)
88 before_filter lambda { accept_attribute_as_json attr, force_class }
90 def accept_attribute_as_json(attr, force_class)
91 if params[resource_name].is_a? Hash
92 if params[resource_name][attr].is_a? String
93 params[resource_name][attr] = JSON.parse params[resource_name][attr]
94 if force_class and !params[resource_name][attr].is_a? force_class
95 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
101 def uncamelcase_params_hash_keys
102 self.params = uncamelcase_hash_keys(params)
105 def uncamelcase_hash_keys(h, max_depth=-1)
106 if h.is_a? Hash and max_depth != 0
111 elsif k.class == Symbol
112 nk = k.to_s.underscore.to_sym
116 nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
125 :kind => "orvos##{resource_name}List",
128 :next_page_token => "",
130 :items => @objects.as_api_response(:superuser)
132 render json: @object_list