Class: Decidim::Comments::SortedComments

Inherits:
Query
  • Object
show all
Defined in:
decidim-comments/app/queries/decidim/comments/sorted_comments.rb

Overview

A class used to find comments for a commentable resource

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Query

#cached_query, #each, #eager?, #exists?, merge, #none?, #relation?, #|

Constructor Details

#initialize(commentable, options = {}) ⇒ SortedComments

Initializes the class.

commentable = a resource that can have comments options - The Hash options is used to refine the selection ( default: {}):

:order_by - The string order_by to sort by ( optional )


23
24
25
26
27
# File 'decidim-comments/app/queries/decidim/comments/sorted_comments.rb', line 23

def initialize(commentable, options = {})
  options[:order_by] ||= "older"
  @commentable = commentable
  @options = options
end

Instance Attribute Details

#commentableObject (readonly)

Returns the value of attribute commentable.



7
8
9
# File 'decidim-comments/app/queries/decidim/comments/sorted_comments.rb', line 7

def commentable
  @commentable
end

Class Method Details

.for(commentable, options = {}) ⇒ Object

Syntactic sugar to initialize the class and return the queried objects.

commentable - a resource that can have comments options - The Hash options is used to refine the selection ( default: {}):

:order_by - The string order_by to sort by ( optional )


14
15
16
# File 'decidim-comments/app/queries/decidim/comments/sorted_comments.rb', line 14

def self.for(commentable, options = {})
  new(commentable, options).query
end

Instance Method Details

#count_replies(comment) ⇒ Object



48
49
50
51
52
53
54
# File 'decidim-comments/app/queries/decidim/comments/sorted_comments.rb', line 48

def count_replies(comment)
  if comment.comment_threads.size.positive?
    comment.comment_threads.size + comment.comment_threads.sum { |reply| count_replies(reply) }
  else
    0
  end
end

#queryObject

Finds the Comments for a resource that can have comments and eager loads comments replies. It uses Comment’s MAX_DEPTH to load a maximum level of nested replies.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'decidim-comments/app/queries/decidim/comments/sorted_comments.rb', line 32

def query
  scope = base_scope
          .includes(:author, :user_group, :up_votes, :down_votes)

  case @options[:order_by]
  when "recent"
    order_by_recent(scope)
  when "best_rated"
    order_by_best_rated(scope)
  when "most_discussed"
    order_by_most_discussed(scope)
  else
    order_by_older(scope)
  end
end