Commit 176d6e2a authored by Grzegorz Bizon's avatar Grzegorz Bizon

Refactor note awards to reuse `emoji_pattern` and improve validator

parent 83d8185f
......@@ -39,9 +39,11 @@ class Note < ActiveRecord::Base
delegate :name, to: :project, prefix: true
delegate :name, :email, to: :author, prefix: true
before_validation :set_award!
validates :note, :project, presence: true
validates :note, uniqueness: { scope: [:author, :noteable_type, :noteable_id] }, if: ->(n) { n.is_award }
validates :note, format: { with: /\A[-_+[:alnum:]]*\z/ }, if: -> (n){ n.is_award }
validates :note, inclusion: { in: Emoji.emojis_names }, if: ->(n) { n.is_award }
validates :line_code, format: { with: /\A[a-z0-9]+_\d+_\d+\Z/ }, allow_blank: true
# Attachments are deprecated and are handled by Markdown uploader
validates :attachment, file_size: { maximum: :max_attachment_size }
......@@ -72,7 +74,6 @@ class Note < ActiveRecord::Base
serialize :st_diff
before_create :set_diff, if: ->(n) { n.line_code.present? }
before_validation :set_award!
class << self
def discussions_from_notes(notes)
......@@ -351,36 +352,31 @@ class Note < ActiveRecord::Base
!system?
end
# Checks if note is an award added from an issue comment.
# Checks if note is an award added as a comment
#
# If note is an award, this method sets is_award to true,
# and changes note content to award-emoji name.
#
# Awards are only supported for issue comments.
# If note is an award, this method sets is_award to true
# and changes content of the note to award name.
#
# Method is executed as a before_validation callback.
#
def set_award!
return unless supports_awards? && contains_emoji_only?
return unless awards_supported? && contains_emoji_only?
self.is_award = true
self.note = award_emoji_name
end
def supports_awards?
noteable.kind_of?(Issue) ||
noteable.is_a?(MergeRequest)
end
private
def awards_supported?
noteable.kind_of?(Issue) || noteable.is_a?(MergeRequest)
end
def contains_emoji_only?
(note =~ /\A:[-_+[:alnum:]]*:\s?\z/) ? true : false
emoji_only_pattern = /\A#{Gitlab::Markdown::EmojiFilter.emoji_pattern}\s?\Z/
(note =~ emoji_only_pattern) ? true : false
end
def award_emoji_name
return nil unless contains_emoji_only?
note.match(/\A:([-_+[:alnum:]]*):\s?/)[1]
note.match(Gitlab::Markdown::EmojiFilter.emoji_pattern)[1]
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment