Class: Minbox::Inbox

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/minbox/inbox.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root_dir:) ⇒ Inbox

Returns a new instance of Inbox.



12
13
14
15
16
# File 'lib/minbox/inbox.rb', line 12

def initialize(root_dir:)
  @semaphore = Mutex.new
  start_listening(root_dir)
  empty!
end

Class Method Details

.instance(root_dir:) ⇒ Object



7
8
9
10
# File 'lib/minbox/inbox.rb', line 7

def self.instance(root_dir:)
  @instances ||= {}
  @instances[root_dir] ||= new(root_dir: root_dir)
end

Instance Method Details

#eachObject



54
55
56
57
58
# File 'lib/minbox/inbox.rb', line 54

def each
  @emails.each do |id, email|
    yield email
  end
end

#emails(count: 0) ⇒ Object



18
19
20
21
22
23
# File 'lib/minbox/inbox.rb', line 18

def emails(count: 0)
  wait_until { |x| x.count >= count } if count > 0
  with_lock do |emails|
    emails.values
  end
end

#empty!Object



48
49
50
51
52
# File 'lib/minbox/inbox.rb', line 48

def empty!
  with_lock do
    @emails = {}
  end
end

#open(subject:) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/minbox/inbox.rb', line 40

def open(subject:)
  wait_until do
    emails.find do |email|
      subject.is_a?(String) ? email.subject == subject : email.subject.match?(subject)
    end
  end
end

#wait_until(seconds: 10, wait: 0.1) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/minbox/inbox.rb', line 25

def wait_until(seconds: 10, wait: 0.1)
  iterations = (seconds / wait).to_i
  iterations.times do
    result = yield(self)
    return result if result

    sleep wait
  end
  nil
end

#wait_until!(*args, &block) ⇒ Object



36
37
38
# File 'lib/minbox/inbox.rb', line 36

def wait_until!(*args, &block)
  raise "timeout: expired. #{args}" unless wait_until(*args, &block)
end