Module: ActsAsNewsletter::Model::ClassMethods

Defined in:
lib/acts_as_newsletter/model.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#config_procObject (readonly)

Returns the value of attribute config_proc.



23
24
25
# File 'lib/acts_as_newsletter/model.rb', line 23

def config_proc
  @config_proc
end

Instance Method Details

#acts_as_newsletter(&config) ⇒ Object



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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/acts_as_newsletter/model.rb', line 25

def acts_as_newsletter &config
  # Store config proc to be dynamically run when sending a newsletter
  @config_proc = config

  # Define state machine
  class_eval do
    state_machine :state, initial: :draft do

      event :written do
        transition draft: :ready
      end

      event :ready_canceled do
        transition ready: :draft
      end

      event :prepare_sending do
        transition ready: :sending
      end
      before_transition on: :prepare_sending, do: :prepare_emails

      event :sending_complete do
        transition sending: :sent
      end

      state :draft do
        # If readied is set to true, then we transition to the `ready`
        # state so it can be matched when calling `::next_newsletter`
        before_validation do
          written! if readied
        end
      end

      state :ready do
        before_validation do
          ready_canceled! if !readied
        end
      end

      state :sending do
        # When we're sending, saving serializes current emails list
        # to only store remaining recipients and updates sent counter
        #
        before_validation do
          if chunk_sent
            self.recipients = emails.join("|")
            self.sent_count += emails.length
            # Transition to :sent state when complete
            sending_complete! if sent_count == recipients_count
          end
        end

        # Avoids multiple calls to save to run into the above
        # before_validation hook without the next chunk being really sent
        #
        after_save do
          self.chunk_sent = false if chunk_sent
          @emails = nil
        end
      end
    end
  end
end

#next_newsletterObject

Finds first newsletter being sent or ready



97
98
99
# File 'lib/acts_as_newsletter/model.rb', line 97

def next_newsletter
  where(state: :sending).first or where(state: :ready).first
end

#send_next!Object

Send next newsletter if one is ready



91
92
93
# File 'lib/acts_as_newsletter/model.rb', line 91

def send_next!
  (newsletter = next_newsletter) and newsletter.send_newsletter!
end