discussion.rb 2.3 KB
Newer Older
1
class Discussion
2 3 4 5 6
  cattr_accessor :memoized_values, instance_accessor: false do
    []
  end

  include ResolvableDiscussion
7

D
Douwe Maan 已提交
8
  attr_reader :notes, :noteable
9 10 11 12 13 14 15 16 17 18 19

  delegate  :created_at,
            :project,
            :author,

            :noteable,
            :for_commit?,
            :for_merge_request?,

            to: :first_note

20 21 22
  def self.build(notes, noteable = nil)
    notes.first.discussion_class(noteable).new(notes, noteable)
  end
23

24 25 26
  def self.build_collection(notes, noteable = nil)
    notes.group_by { |n| n.discussion_id(noteable) }.values.map { |notes| build(notes, noteable) }
  end
27

28 29
  def self.discussion_id(note)
    Digest::SHA1.hexdigest(build_discussion_id(note).join("-"))
30 31
  end

32 33 34
  # Optionally override the discussion ID at runtime depending on circumstances
  def self.override_discussion_id(note)
    nil
35 36
  end

D
Douwe Maan 已提交
37
  def self.build_discussion_id_base(note)
38 39
    noteable_id = note.noteable_id || note.commit_id
    [:discussion, note.noteable_type.try(:underscore), noteable_id]
40 41
  end

D
Douwe Maan 已提交
42
  # Returns an array of discussion ID components
D
Douwe Maan 已提交
43 44
  def self.build_discussion_id(note)
    [*build_discussion_id_base(note), SecureRandom.hex]
45 46 47 48 49
  end

  def initialize(notes, noteable = nil)
    @notes = notes
    @noteable = noteable
50 51
  end

D
Douwe Maan 已提交
52 53 54 55 56 57 58
  def ==(other)
    other.class == self.class &&
      other.noteable == self.noteable &&
      other.id == self.id &&
      other.notes == self.notes
  end

59 60 61 62 63 64 65 66
  def last_updated_at
    last_note.created_at
  end

  def last_updated_by
    last_note.author
  end

67
  def id
68
    first_note.discussion_id(noteable)
69
  end
70

D
Douwe Maan 已提交
71
  alias_method :to_param, :id
72 73

  def diff_discussion?
74 75 76
    false
  end

D
Douwe Maan 已提交
77
  def individual_note?
78
    false
79 80
  end

81 82 83 84
  def new_discussion?
    notes.length == 1
  end

85
  def last_note
86
    @last_note ||= notes.last
87
  end
88

D
Douwe Maan 已提交
89
  def collapsed?
D
Douwe Maan 已提交
90
    resolved?
D
Douwe Maan 已提交
91 92
  end

93
  def expanded?
D
Douwe Maan 已提交
94
    !collapsed?
95 96 97
  end

  def reply_attributes
D
Douwe Maan 已提交
98
    first_note.slice(:type, :noteable_type, :noteable_id, :commit_id, :discussion_id)
99
  end
100 101 102 103

  private

  def update
104 105 106
    # Do not select `Note.resolvable`, so that system notes remain in the collection
    notes_relation = Note.where(id: notes.map(&:id))

107 108 109
    yield(notes_relation)

    # Set the notes array to the updated notes
110
    @notes = notes_relation.fresh.to_a
111

112
    self.class.memoized_values.each do |var|
113 114
      instance_variable_set(:"@#{var}", nil)
    end
115
  end
116
end