Class: Emailer::MailQueue

Inherits:
Object
  • Object
show all
Defined in:
lib/emailer/mail_queue.rb

Instance Method Summary collapse

Constructor Details

#initialize(smtp) ⇒ MailQueue

Returns a new instance of MailQueue.



4
5
6
7
# File 'lib/emailer/mail_queue.rb', line 4

def initialize(smtp)
  @smtp = smtp
  @queue = []
end

Instance Method Details

#add(mail, &callback) ⇒ Object



17
18
19
20
21
22
# File 'lib/emailer/mail_queue.rb', line 17

def add(mail, &callback)
  mail[:content_type] ||= 'text/plain'
  mail[:encoding] ||= 'utf-8'
  
  @queue << mail.merge(:callback => callback)
end

#add_html(mail, &callback) ⇒ Object



24
25
26
# File 'lib/emailer/mail_queue.rb', line 24

def add_html(mail, &callback)
  add({ :content_type => 'text/html' }.merge(mail), &callback)
end

#empty?Boolean

Returns:

  • (Boolean)


9
10
11
# File 'lib/emailer/mail_queue.rb', line 9

def empty?
  @queue.empty?
end

#lastObject



28
29
30
# File 'lib/emailer/mail_queue.rb', line 28

def last
  @queue.last
end

#lengthObject



13
14
15
# File 'lib/emailer/mail_queue.rb', line 13

def length
  @queue.length
end

#process(tcount = 4) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/emailer/mail_queue.rb', line 32

def process(tcount = 4)
  tcount = length if length < tcount
  
  threads = []
  mutex = Mutex.new
  
  tcount.times do |n|
    threads << Thread.new(n) do |tid|
      while !empty?
        send_mail mutex
      end
    end
  end
  
  threads.each { |thr| thr.join }
end

#send_mail(mutex) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/emailer/mail_queue.rb', line 49

def send_mail(mutex)
  smtp = @smtp.clone
  smtp.open do
    while mail = mutex.synchronize { @queue.shift }
      result = smtp.send_mail mail
      mail[:callback].call(result, mail) if mail[:callback]
    end
  end
end