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: 401
36 @objects ||= model_class.all
41 render_for_api :superuser, json: @object
45 @attrs = params[resource_name]
47 raise "no #{resource_name} (or #{resource_name.camelcase(:lower)}) provided with request #{params.inspect}"
49 if @attrs.class == String
50 @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
52 @object = model_class.new @attrs
58 @attrs = params[resource_name]
59 if @attrs.is_a? String
60 @attrs = uncamelcase_hash_keys(JSON.parse @attrs)
62 @object.update_attributes @attrs
69 controller_name.classify.constantize
72 def resource_name # params[] key used by client
73 controller_name.singularize
76 def find_object_by_uuid
77 if params[:id] and params[:id].match /\D/
78 params[:uuid] = params.delete :id
80 @object = model_class.where('uuid=?', params[:uuid]).first
83 def self.accept_attribute_as_json(attr, force_class=nil)
84 before_filter lambda { accept_attribute_as_json attr, force_class }
86 def accept_attribute_as_json(attr, force_class)
87 if params[resource_name].is_a? Hash
88 if params[resource_name][attr].is_a? String
89 params[resource_name][attr] = JSON.parse params[resource_name][attr]
90 if force_class and !params[resource_name][attr].is_a? force_class
91 raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
97 def uncamelcase_params_hash_keys
98 self.params = uncamelcase_hash_keys(params)
101 def uncamelcase_hash_keys(h, max_depth=-1)
102 if h.is_a? Hash and max_depth != 0
107 elsif k.class == Symbol
108 nk = k.to_s.underscore.to_sym
112 nh[nk] = uncamelcase_hash_keys(v, max_depth-1)
121 :kind => "orvos##{resource_name}List",
124 :next_page_token => "",
126 :items => @objects.as_api_response(:superuser)
128 render json: @object_list