Merge branch '2884-improved-picker' closes #2884
[arvados.git] / apps / workbench / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include ArvadosApiClientHelper
3   include ApplicationHelper
4
5   respond_to :html, :json, :js
6   protect_from_forgery
7
8   ERROR_ACTIONS = [:render_error, :render_not_found]
9
10   around_filter :thread_clear
11   around_filter :thread_with_mandatory_api_token, except: ERROR_ACTIONS
12   around_filter :thread_with_optional_api_token
13   before_filter :check_user_agreements, except: ERROR_ACTIONS
14   before_filter :check_user_notifications, except: ERROR_ACTIONS
15   before_filter :find_object_by_uuid, except: [:index, :choose] + ERROR_ACTIONS
16   theme :select_theme
17
18   begin
19     rescue_from Exception,
20     :with => :render_exception
21     rescue_from ActiveRecord::RecordNotFound,
22     :with => :render_not_found
23     rescue_from ActionController::RoutingError,
24     :with => :render_not_found
25     rescue_from ActionController::UnknownController,
26     :with => :render_not_found
27     rescue_from ::AbstractController::ActionNotFound,
28     :with => :render_not_found
29   end
30
31   def unprocessable(message=nil)
32     @errors ||= []
33
34     @errors << message if message
35     render_error status: 422
36   end
37
38   def render_error(opts)
39     opts = {status: 500}.merge opts
40     respond_to do |f|
41       # json must come before html here, so it gets used as the
42       # default format when js is requested by the client. This lets
43       # ajax:error callback parse the response correctly, even though
44       # the browser can't.
45       f.json { render opts.merge(json: {success: false, errors: @errors}) }
46       f.html { render opts.merge(controller: 'application', action: 'error') }
47     end
48   end
49
50   def render_exception(e)
51     logger.error e.inspect
52     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
53     if @object.andand.errors.andand.full_messages.andand.any?
54       @errors = @object.errors.full_messages
55     else
56       @errors = [e.to_s]
57     end
58     self.render_error status: 422
59   end
60
61   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
62     logger.error e.inspect
63     @errors = ["Path not found"]
64     self.render_error status: 404
65   end
66
67   def find_objects_for_index
68     @limit ||= 200
69     if params[:limit]
70       @limit = params[:limit].to_i
71     end
72
73     @offset ||= 0
74     if params[:offset]
75       @offset = params[:offset].to_i
76     end
77
78     @filters ||= []
79     if params[:filters]
80       filters = params[:filters]
81       if filters.is_a? String
82         filters = Oj.load filters
83       end
84       @filters += filters
85     end
86
87     @objects ||= model_class
88     @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
89   end
90
91   def render_index
92     respond_to do |f|
93       f.json { render json: @objects }
94       f.html {
95         if params['tab_pane']
96           comparable = self.respond_to? :compare
97           render(partial: 'show_' + params['tab_pane'].downcase,
98                  locals: { comparable: comparable, objects: @objects })
99         else
100           render
101         end
102       }
103       f.js { render }
104     end
105   end
106
107   def index
108     find_objects_for_index if !@objects
109     render_index
110   end
111
112   helper_method :next_page_offset
113   def next_page_offset
114     if @objects.respond_to?(:result_offset) and
115         @objects.respond_to?(:result_limit) and
116         @objects.respond_to?(:items_available)
117       next_offset = @objects.result_offset + @objects.result_limit
118       if next_offset < @objects.items_available
119         next_offset
120       else
121         nil
122       end
123     end
124   end
125
126   def show
127     if !@object
128       return render_not_found("object not found")
129     end
130     respond_to do |f|
131       f.json { render json: @object.attributes.merge(href: url_for(@object)) }
132       f.html {
133         if params['tab_pane']
134           comparable = self.respond_to? :compare
135           render(partial: 'show_' + params['tab_pane'].downcase,
136                  locals: { comparable: comparable, objects: @objects })
137         elsif request.method.in? ['GET', 'HEAD']
138           render
139         else
140           redirect_to params[:return_to] || @object
141         end
142       }
143       f.js { render }
144     end
145   end
146
147   def choose
148     params[:limit] ||= 40
149     if !@objects
150       if params[:project_uuid] and !params[:project_uuid].empty?
151         # We want the chooser to show objects of the controllers's model_class
152         # type within a specific project specified by project_uuid, so fetch the
153         # project and request the contents of the project filtered on the
154         # controllers's model_class kind.
155         @objects = Group.find(params[:project_uuid]).contents({:filters => [['uuid', 'is_a', "arvados\##{ArvadosApiClient.class_kind(model_class)}"]]})
156       end
157       find_objects_for_index if !@objects
158     end
159     respond_to do |f|
160       if params[:partial]
161         f.json {
162           render json: {
163             content: render_to_string(partial: "choose_rows.html",
164                                       formats: [:html],
165                                       locals: {
166                                         multiple: params[:multiple]
167                                       }),
168             next_page_href: @next_page_href
169           }
170         }
171       end
172       f.js {
173         render partial: 'choose', locals: {multiple: params[:multiple]}
174       }
175     end
176   end
177
178   def render_content
179     if !@object
180       return render_not_found("object not found")
181     end
182   end
183
184   def new
185     @object = model_class.new
186   end
187
188   def update
189     @updates ||= params[@object.resource_param_name.to_sym]
190     @updates.keys.each do |attr|
191       if @object.send(attr).is_a? Hash
192         if @updates[attr].is_a? String
193           @updates[attr] = Oj.load @updates[attr]
194         end
195         if params[:merge] || params["merge_#{attr}".to_sym]
196           # Merge provided Hash with current Hash, instead of
197           # replacing.
198           @updates[attr] = @object.send(attr).with_indifferent_access.
199             deep_merge(@updates[attr].with_indifferent_access)
200         end
201       end
202     end
203     if @object.update_attributes @updates
204       show
205     else
206       self.render_error status: 422
207     end
208   end
209
210   def create
211     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
212     @new_resource_attrs ||= {}
213     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
214     @object ||= model_class.new @new_resource_attrs, params["options"]
215     if @object.save
216       respond_to do |f|
217         f.json { render json: @object.attributes.merge(href: url_for(@object)) }
218         f.html {
219           redirect_to @object
220         }
221         f.js { render }
222       end
223     else
224       self.render_error status: 422
225     end
226   end
227
228   # Clone the given object, merging any attribute values supplied as
229   # with a create action.
230   def copy
231     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
232     @new_resource_attrs ||= {}
233     @object = @object.dup
234     @object.update_attributes @new_resource_attrs
235     if not @new_resource_attrs[:name] and @object.respond_to? :name
236       if @object.name and @object.name != ''
237         @object.name = "Copy of #{@object.name}"
238       else
239         @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
240       end
241     end
242     @object.save!
243     show
244   end
245
246   def destroy
247     if @object.destroy
248       respond_to do |f|
249         f.json { render json: @object }
250         f.html {
251           redirect_to(params[:return_to] || :back)
252         }
253         f.js { render }
254       end
255     else
256       self.render_error status: 422
257     end
258   end
259
260   def current_user
261     return Thread.current[:user] if Thread.current[:user]
262
263     if Thread.current[:arvados_api_token]
264       if session[:user]
265         if session[:user][:is_active] != true
266           Thread.current[:user] = User.current
267         else
268           Thread.current[:user] = User.new(session[:user])
269         end
270       else
271         Thread.current[:user] = User.current
272       end
273     else
274       logger.error "No API token in Thread"
275       return nil
276     end
277   end
278
279   def model_class
280     controller_name.classify.constantize
281   end
282
283   def breadcrumb_page_name
284     (@breadcrumb_page_name ||
285      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
286      action_name)
287   end
288
289   def index_pane_list
290     %w(Recent)
291   end
292
293   def show_pane_list
294     %w(Attributes Advanced)
295   end
296
297   protected
298
299   def redirect_to_login
300     respond_to do |f|
301       f.html {
302         if request.method.in? ['GET', 'HEAD']
303           redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
304         else
305           flash[:error] = "Either you are not logged in, or your session has timed out. I can't automatically log you in and re-attempt this request."
306           redirect_to :back
307         end
308       }
309       f.json {
310         @errors = ['You do not seem to be logged in. You did not supply an API token with this request, and your session (if any) has timed out.']
311         self.render_error status: 422
312       }
313     end
314     false  # For convenience to return from callbacks
315   end
316
317   def using_specific_api_token(api_token)
318     start_values = {}
319     [:arvados_api_token, :user].each do |key|
320       start_values[key] = Thread.current[key]
321     end
322     Thread.current[:arvados_api_token] = api_token
323     Thread.current[:user] = nil
324     begin
325       yield
326     ensure
327       start_values.each_key { |key| Thread.current[key] = start_values[key] }
328     end
329   end
330
331   def find_object_by_uuid
332     if params[:id] and params[:id].match /\D/
333       params[:uuid] = params.delete :id
334     end
335     if not model_class
336       @object = nil
337     elsif params[:uuid].is_a? String
338       if params[:uuid].empty?
339         @object = nil
340       else
341         if (model_class != Link and
342             resource_class_for_uuid(params[:uuid]) == Link)
343           @name_link = Link.find(params[:uuid])
344           @object = model_class.find(@name_link.head_uuid)
345         else
346           @object = model_class.find(params[:uuid])
347         end
348       end
349     else
350       @object = model_class.where(uuid: params[:uuid]).first
351     end
352   end
353
354   def thread_clear
355     Thread.current[:arvados_api_token] = nil
356     Thread.current[:user] = nil
357     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
358     yield
359     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
360   end
361
362   def thread_with_api_token(login_optional = false)
363     begin
364       try_redirect_to_login = true
365       if params[:api_token]
366         try_redirect_to_login = false
367         Thread.current[:arvados_api_token] = params[:api_token]
368         # Before copying the token into session[], do a simple API
369         # call to verify its authenticity.
370         if verify_api_token
371           session[:arvados_api_token] = params[:api_token]
372           u = User.current
373           session[:user] = {
374             uuid: u.uuid,
375             email: u.email,
376             first_name: u.first_name,
377             last_name: u.last_name,
378             is_active: u.is_active,
379             is_admin: u.is_admin,
380             prefs: u.prefs
381           }
382           if !request.format.json? and request.method.in? ['GET', 'HEAD']
383             # Repeat this request with api_token in the (new) session
384             # cookie instead of the query string.  This prevents API
385             # tokens from appearing in (and being inadvisedly copied
386             # and pasted from) browser Location bars.
387             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
388           else
389             yield
390           end
391         else
392           @errors = ['Invalid API token']
393           self.render_error status: 401
394         end
395       elsif session[:arvados_api_token]
396         # In this case, the token must have already verified at some
397         # point, but it might have been revoked since.  We'll try
398         # using it, and catch the exception if it doesn't work.
399         try_redirect_to_login = false
400         Thread.current[:arvados_api_token] = session[:arvados_api_token]
401         begin
402           yield
403         rescue ArvadosApiClient::NotLoggedInException
404           try_redirect_to_login = true
405         end
406       else
407         logger.debug "No token received, session is #{session.inspect}"
408       end
409       if try_redirect_to_login
410         unless login_optional
411           redirect_to_login
412         else
413           # login is optional for this route so go on to the regular controller
414           Thread.current[:arvados_api_token] = nil
415           yield
416         end
417       end
418     ensure
419       # Remove token in case this Thread is used for anything else.
420       Thread.current[:arvados_api_token] = nil
421     end
422   end
423
424   def thread_with_mandatory_api_token
425     thread_with_api_token(true) do
426       if Thread.current[:arvados_api_token]
427         yield
428       elsif session[:arvados_api_token]
429         # Expired session. Clear it before refreshing login so that,
430         # if this login procedure fails, we end up showing the "please
431         # log in" page instead of getting stuck in a redirect loop.
432         session.delete :arvados_api_token
433         redirect_to_login
434       else
435         render 'users/welcome'
436       end
437     end
438   end
439
440   # This runs after thread_with_mandatory_api_token in the filter chain.
441   def thread_with_optional_api_token
442     if Thread.current[:arvados_api_token]
443       # We are already inside thread_with_mandatory_api_token.
444       yield
445     else
446       # We skipped thread_with_mandatory_api_token. Use the optional version.
447       thread_with_api_token(true) do
448         yield
449       end
450     end
451   end
452
453   def verify_api_token
454     begin
455       Link.where(uuid: 'just-verifying-my-api-token')
456       true
457     rescue ArvadosApiClient::NotLoggedInException
458       false
459     end
460   end
461
462   def ensure_current_user_is_admin
463     unless current_user and current_user.is_admin
464       @errors = ['Permission denied']
465       self.render_error status: 401
466     end
467   end
468
469   def check_user_agreements
470     if current_user && !current_user.is_active
471       if not current_user.is_invited
472         return render 'users/inactive'
473       end
474       signatures = UserAgreement.signatures
475       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
476       @required_user_agreements = UserAgreement.all.map do |ua|
477         if not @signed_ua_uuids.index ua.uuid
478           Collection.find(ua.uuid)
479         end
480       end.compact
481       if @required_user_agreements.empty?
482         # No agreements to sign. Perhaps we just need to ask?
483         current_user.activate
484         if !current_user.is_active
485           logger.warn "#{current_user.uuid.inspect}: " +
486             "No user agreements to sign, but activate failed!"
487         end
488       end
489       if !current_user.is_active
490         render 'user_agreements/index'
491       end
492     end
493     true
494   end
495
496   def select_theme
497     return Rails.configuration.arvados_theme
498   end
499
500   @@notification_tests = []
501
502   @@notification_tests.push lambda { |controller, current_user|
503     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
504       return nil
505     end
506     return lambda { |view|
507       view.render partial: 'notifications/ssh_key_notification'
508     }
509   }
510
511   #@@notification_tests.push lambda { |controller, current_user|
512   #  Job.limit(1).where(created_by: current_user.uuid).each do
513   #    return nil
514   #  end
515   #  return lambda { |view|
516   #    view.render partial: 'notifications/jobs_notification'
517   #  }
518   #}
519
520   @@notification_tests.push lambda { |controller, current_user|
521     Collection.limit(1).where(created_by: current_user.uuid).each do
522       return nil
523     end
524     return lambda { |view|
525       view.render partial: 'notifications/collections_notification'
526     }
527   }
528
529   @@notification_tests.push lambda { |controller, current_user|
530     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
531       return nil
532     end
533     return lambda { |view|
534       view.render partial: 'notifications/pipelines_notification'
535     }
536   }
537
538   def check_user_notifications
539     return if params['tab_pane']
540
541     @notification_count = 0
542     @notifications = []
543
544     if current_user
545       @showallalerts = false
546       @@notification_tests.each do |t|
547         a = t.call(self, current_user)
548         if a
549           @notification_count += 1
550           @notifications.push a
551         end
552       end
553     end
554
555     if @notification_count == 0
556       @notification_count = ''
557     end
558   end
559
560   helper_method :all_projects
561   def all_projects
562     @all_projects ||= Group.
563       filter([['group_class','in',['project','folder']]]).order('name')
564   end
565
566   helper_method :my_projects
567   def my_projects
568     return @my_projects if @my_projects
569     @my_projects = []
570     root_of = {}
571     all_projects.each do |g|
572       root_of[g.uuid] = g.owner_uuid
573       @my_projects << g
574     end
575     done = false
576     while not done
577       done = true
578       root_of = root_of.each_with_object({}) do |(child, parent), h|
579         if root_of[parent]
580           h[child] = root_of[parent]
581           done = false
582         else
583           h[child] = parent
584         end
585       end
586     end
587     @my_projects = @my_projects.select do |g|
588       root_of[g.uuid] == current_user.uuid
589     end
590   end
591
592   helper_method :projects_shared_with_me
593   def projects_shared_with_me
594     my_project_uuids = my_projects.collect &:uuid
595     all_projects.reject { |x| x.uuid.in? my_project_uuids }
596   end
597
598   helper_method :recent_jobs_and_pipelines
599   def recent_jobs_and_pipelines
600     (Job.limit(10) |
601      PipelineInstance.limit(10)).
602       sort_by do |x|
603       x.finished_at || x.started_at || x.created_at rescue x.created_at
604     end
605   end
606
607   helper_method :my_project_tree
608   def my_project_tree
609     build_project_trees
610     @my_project_tree
611   end
612
613   helper_method :shared_project_tree
614   def shared_project_tree
615     build_project_trees
616     @shared_project_tree
617   end
618
619   def build_project_trees
620     return if @my_project_tree and @shared_project_tree
621     parent_of = {current_user.uuid => 'me'}
622     all_projects.each do |ob|
623       parent_of[ob.uuid] = ob.owner_uuid
624     end
625     children_of = {false => [], 'me' => [current_user]}
626     all_projects.each do |ob|
627       if ob.owner_uuid != current_user.uuid and
628           not parent_of.has_key? ob.owner_uuid
629         parent_of[ob.uuid] = false
630       end
631       children_of[parent_of[ob.uuid]] ||= []
632       children_of[parent_of[ob.uuid]] << ob
633     end
634     buildtree = lambda do |children_of, root_uuid=false|
635       tree = {}
636       children_of[root_uuid].andand.each do |ob|
637         tree[ob] = buildtree.call(children_of, ob.uuid)
638       end
639       tree
640     end
641     sorted_paths = lambda do |tree, depth=0|
642       paths = []
643       tree.keys.sort_by { |ob|
644         ob.is_a?(String) ? ob : ob.friendly_link_name
645       }.each do |ob|
646         paths << {object: ob, depth: depth}
647         paths += sorted_paths.call tree[ob], depth+1
648       end
649       paths
650     end
651     @my_project_tree =
652       sorted_paths.call buildtree.call(children_of, 'me')
653     @shared_project_tree =
654       sorted_paths.call({'Shared with me' =>
655                           buildtree.call(children_of, false)})
656   end
657
658   helper_method :get_object
659   def get_object uuid
660     if @get_object.nil? and @objects
661       @get_object = @objects.each_with_object({}) do |object, h|
662         h[object.uuid] = object
663       end
664     end
665     @get_object ||= {}
666     @get_object[uuid]
667   end
668
669   helper_method :project_breadcrumbs
670   def project_breadcrumbs
671     crumbs = []
672     current = @name_link || @object
673     while current
674       if current.is_a?(Group) and current.group_class.in?(['project','folder'])
675         crumbs.prepend current
676       end
677       if current.is_a? Link
678         current = Group.find?(current.tail_uuid)
679       else
680         current = Group.find?(current.owner_uuid)
681       end
682     end
683     crumbs
684   end
685
686   helper_method :current_project_uuid
687   def current_project_uuid
688     if @object.is_a? Group and @object.group_class.in?(['project','folder'])
689       @object.uuid
690     elsif @name_link.andand.tail_uuid
691       @name_link.tail_uuid
692     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
693       @object.owner_uuid
694     else
695       nil
696     end
697   end
698
699   # helper method to get links for given object or uuid
700   helper_method :links_for_object
701   def links_for_object object_or_uuid
702     raise ArgumentError, 'No input argument' unless object_or_uuid
703     preload_links_for_objects([object_or_uuid])
704     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
705     @all_links_for[uuid] ||= []
706   end
707
708   # helper method to preload links for given objects and uuids
709   helper_method :preload_links_for_objects
710   def preload_links_for_objects objects_and_uuids
711     @all_links_for ||= {}
712
713     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
714     return @all_links_for if objects_and_uuids.empty?
715
716     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
717
718     # if already preloaded for all of these uuids, return
719     if not uuids.select { |x| @all_links_for[x].nil? }.any?
720       return @all_links_for
721     end
722
723     uuids.each do |x|
724       @all_links_for[x] = []
725     end
726
727     # TODO: make sure we get every page of results from API server
728     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
729       @all_links_for[link.head_uuid] << link
730     end
731     @all_links_for
732   end
733
734   # helper method to get a certain number of objects of a specific type
735   # this can be used to replace any uses of: "dataclass.limit(n)"
736   helper_method :get_n_objects_of_class
737   def get_n_objects_of_class dataclass, size
738     @objects_map_for ||= {}
739
740     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
741     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
742
743     # if the objects_map_for has a value for this dataclass, and the
744     # size used to retrieve those objects is equal, return it
745     size_key = "#{dataclass.name}_size"
746     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
747         (@objects_map_for[size_key] == size)
748       return @objects_map_for[dataclass.name]
749     end
750
751     @objects_map_for[size_key] = size
752     @objects_map_for[dataclass.name] = dataclass.limit(size)
753   end
754
755   # helper method to get collections for the given uuid
756   helper_method :collections_for_object
757   def collections_for_object uuid
758     raise ArgumentError, 'No input argument' unless uuid
759     preload_collections_for_objects([uuid])
760     @all_collections_for[uuid] ||= []
761   end
762
763   # helper method to preload collections for the given uuids
764   helper_method :preload_collections_for_objects
765   def preload_collections_for_objects uuids
766     @all_collections_for ||= {}
767
768     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
769     return @all_collections_for if uuids.empty?
770
771     # if already preloaded for all of these uuids, return
772     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
773       return @all_collections_for
774     end
775
776     uuids.each do |x|
777       @all_collections_for[x] = []
778     end
779
780     # TODO: make sure we get every page of results from API server
781     Collection.where(uuid: uuids).each do |collection|
782       @all_collections_for[collection.uuid] << collection
783     end
784     @all_collections_for
785   end
786
787   # helper method to get log collections for the given log
788   helper_method :log_collections_for_object
789   def log_collections_for_object log
790     raise ArgumentError, 'No input argument' unless log
791
792     preload_log_collections_for_objects([log])
793
794     uuid = log
795     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
796     if fixup && fixup.size>1
797       uuid = fixup[1]
798     end
799
800     @all_log_collections_for[uuid] ||= []
801   end
802
803   # helper method to preload collections for the given uuids
804   helper_method :preload_log_collections_for_objects
805   def preload_log_collections_for_objects logs
806     @all_log_collections_for ||= {}
807
808     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
809     return @all_log_collections_for if logs.empty?
810
811     uuids = []
812     logs.each do |log|
813       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
814       if fixup && fixup.size>1
815         uuids << fixup[1]
816       else
817         uuids << log
818       end
819     end
820
821     # if already preloaded for all of these uuids, return
822     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
823       return @all_log_collections_for
824     end
825
826     uuids.each do |x|
827       @all_log_collections_for[x] = []
828     end
829
830     # TODO: make sure we get every page of results from API server
831     Collection.where(uuid: uuids).each do |collection|
832       @all_log_collections_for[collection.uuid] << collection
833     end
834     @all_log_collections_for
835   end
836
837   # helper method to get object of a given dataclass and uuid
838   helper_method :object_for_dataclass
839   def object_for_dataclass dataclass, uuid
840     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
841     preload_objects_for_dataclass(dataclass, [uuid])
842     @objects_for[uuid]
843   end
844
845   # helper method to preload objects for given dataclass and uuids
846   helper_method :preload_objects_for_dataclass
847   def preload_objects_for_dataclass dataclass, uuids
848     @objects_for ||= {}
849
850     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
851     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
852
853     return @objects_for if uuids.empty?
854
855     # if already preloaded for all of these uuids, return
856     if not uuids.select { |x| @objects_for[x].nil? }.any?
857       return @objects_for
858     end
859
860     dataclass.where(uuid: uuids).each do |obj|
861       @objects_for[obj.uuid] = obj
862     end
863     @objects_for
864   end
865
866 end