spammable.rb 1.42 KB
Newer Older
1
2
module Spammable
  extend ActiveSupport::Concern
3
4
5
6
7
8
9
10
11
  include Gitlab::AkismetHelper

  module ClassMethods
    def attr_spammable(*attrs)
      attrs.each do |attr|
        spammable_attrs << attr.to_s
      end
    end
  end
12
13

  included do
14
    has_one :user_agent_detail, as: :subject, dependent: :destroy
15
16
    attr_accessor :spam
    after_validation :check_for_spam, on: :create
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

    cattr_accessor :spammable_attrs, instance_accessor: false do
      []
    end
  end

  def can_be_submitted?
    if user_agent_detail
      user_agent_detail.submittable?
    else
      false
    end
  end

  def submit_ham
    return unless akismet_enabled? && can_be_submitted?
    ham!(user_agent_detail, spammable_text, creator)
  end

  def submit_spam
    return unless akismet_enabled? && can_be_submitted?
    spam!(user_agent_detail, spammable_text, creator)
  end

  def spam?(env, user)
    is_spam?(env, user, spammable_text)
43
44
  end

45
  def spam_detected?
46
47
48
49
    @spam
  end

  def check_for_spam
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    self.errors.add(:base, "Your #{self.class.name.underscore} has been recognized as spam and has been discarded.") if spam_detected?
  end

  private

  def spammable_text
    result = []
    self.class.spammable_attrs.each do |entry|
      result << self.send(entry)
    end
    result.reject(&:blank?).join("\n")
  end

  def creator
    if self.author_id
      User.find(self.author_id)
    elsif self.creator_id
      User.find(self.creator_id)
    end
69
70
  end
end