Class: Comment

Inherits:
ApplicationRecord show all
Defined in:
app/models/comment.rb

Overview

A comment can be assigned to any commentable record.

Instance Attribute Summary collapse

Class Method Summary collapse

Methods inherited from ApplicationRecord

convert_labware_to_receptacle_for, find_by_id_or_name, find_by_id_or_name!

Methods included from Squishify

extended

Instance Attribute Details

#keyString

Returns Longer text containing the main body of the comment.

Returns:

  • (String)

    Longer text containing the main body of the comment


14
# File 'app/models/comment.rb', line 14

after_create :trigger_commentable_callback

#titleString

Returns A short string, best used to identify the comment source.

Returns:

  • (String)

    A short string, best used to identify the comment source.


14
# File 'app/models/comment.rb', line 14

after_create :trigger_commentable_callback

Class Method Details

.counts_for(commentables) ⇒ Object

Caution, only works for a single class


19
20
21
# File 'app/models/comment.rb', line 19

def self.counts_for(commentables)
  where(commentable: commentables).group(:commentable_id).count
end

.counts_for_requests(requests) ⇒ Hash

We don't want to load comments upfront, as it can result in a lot of data in some cases. However, we do want to display counts. However when it comes to requests, there are three places we may wish to look:

  • The request itself

  • The receptacle (source receptacle)

  • The labware associated with the receptacle

Rather than having three separate columns, we instead reduce it down to a single place. This method lets us aggregate those counts

Parameters:

  • requests (Array<Request>)

    Requests to get counts for. Preferably with preloaded assets

Returns:

  • (Hash)

    Hash of counts indexed by request_id


36
37
38
39
40
41
42
43
44
45
# File 'app/models/comment.rb', line 36

def self.counts_for_requests(requests) # rubocop:todo Metrics/AbcSize
  all_commentables = requests.flat_map { |request| [request, request.asset, request.asset&.labware] }
  counts = where(commentable: all_commentables.compact).group(:commentable_type, :commentable_id).count
  requests.each_with_object({}) do |request, counter_cache|
    request_count = counts.fetch(['Request', request.id], 0)
    receptacle_count = counts.fetch(['Receptacle', request.asset_id], 0)
    labware_count = counts.fetch(['Labware', request.asset.labware_id], 0)
    counter_cache[request.id] = request_count + receptacle_count + labware_count
  end
end