cirandas.net

ref: master

app/models/concerns/spammable.rb


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module Spammable

  def self.included(recipient)
    #TODO This line crashes the migration which includes the spam attribute to
    #     Task...  =P
    #     No fail-safe until someone find out how to use this without crashing
    #     the migration process
    #raise "This model (#{recipient.to_s}) should have a spam attribute!" if !recipient.new.respond_to?('spam=')
    recipient.extend(ClassMethods)
  end

  module ClassMethods
    def self.extended base
      if base.respond_to?(:scope)
        base.class_eval do
          scope :without_spam, -> { where 'spam IS NULL OR spam = ?', false }
          scope :spam, -> { where 'spam = ?', true }
        end
      end
    end
  end

  def spam?
    !spam.nil? && spam
  end

  def ham?
    !spam.nil? && !spam
  end

  def spam!
    before_spam!
    self.spam = true
    self.save!
    after_spam!
    self
  end

  def ham!
    before_ham!
    self.spam = false
    self.save!
    after_ham!
    self
  end

  def after_spam!; end
  def before_spam!; end

  def after_ham!; end
  def before_ham!; end

  def marked_as_spam
    plugins.dispatch :marked_as_spam, self
  end

  def marked_as_ham
    plugins.dispatch :marked_as_ham, self
  end

  def check_for_spam
    plugins.dispatch :check_for_spam, self
  end

end