BigW Consortium Gitlab

spammable.rb 1.5 KB
Newer Older
1 2
module Spammable
  extend ActiveSupport::Concern
3 4

  module ClassMethods
5 6
    def attr_spammable(attr, options = {})
      spammable_attrs << [attr.to_s, options]
7 8
    end
  end
9 10

  included do
11
    has_one :user_agent_detail, as: :subject, dependent: :destroy
12

13
    attr_accessor :spam
14 15

    after_validation :check_for_spam, on: :create
16 17 18 19

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

    delegate :ip_address, :user_agent, to: :user_agent_detail, allow_nil: true
22 23
  end

24
  def submittable_as_spam?
25
    if user_agent_detail
26
      user_agent_detail.submittable? && current_application_settings.akismet_enabled
27 28 29 30 31
    else
      false
    end
  end

32
  def spam?
33 34 35
    @spam
  end

36
  def check_for_spam
37 38 39 40
    self.errors.add(:base, "Your #{self.class.name.underscore} has been recognized as spam and has been discarded.") if spam?
  end

  def spam_title
41
    attr = self.class.spammable_attrs.find do |_, options|
42 43 44
      options.fetch(:spam_title, false)
    end

45
    public_send(attr.first) if attr && respond_to?(attr.first.to_sym)
46 47 48
  end

  def spam_description
49
    attr = self.class.spammable_attrs.find do |_, options|
50 51
      options.fetch(:spam_description, false)
    end
52

53
    public_send(attr.first) if attr && respond_to?(attr.first.to_sym)
54
  end
55 56

  def spammable_text
57 58
    result = self.class.spammable_attrs.map do |attr|
      public_send(attr.first)
59
    end
60

61 62 63
    result.reject(&:blank?).join("\n")
  end

64 65
  # Override in Spammable if further checks are necessary
  def check_for_spam?
66
    true
67 68
  end
end