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