summaryrefslogtreecommitdiff
path: root/fake-service/lib/pixelated_service/sorted_mail.rb
blob: 555d4bd444214aa148746e8550af042585f70b5e (plain)
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
module PixelatedService
  class SortedMail
    include Enumerable

    NEWEST_FIRST = lambda do |l,r|
        (r.headers[:date] || Time.now) <=> (l.headers[:date] || Time.now)
    end

    def initialize(&block)
      @mails = {}
      @mail_order = []
      @sort_procedure = block || NEWEST_FIRST
    end

    def []=(k, v)
      @mails[k] = v
      @mail_order << v
      sort_mail_order!
      v
    end

    def [](k)
      @mails[k]
    end

    def delete(k)
      v = @mails.delete(k)
      @mail_order.delete(v)
      v
    end

    def add_all(hs)
      hs.each do |h,v|
        @mails[h] = v
        @mail_order << v
      end
      sort_mail_order!
      self
    end

    def length
      @mails.length
    end

    def sort_mail_order!
      @mail_order.sort!(&@sort_procedure)
      @mail_order.compact!
      @mail_order.uniq!
    end

    def each
      @mail_order.each do |m|
        yield m
      end
    end
  end
end