]> git.cworth.org Git - sup/blob - lib/sup/account.rb
Merge branch 'buffer-rolling'
[sup] / lib / sup / account.rb
1 module Redwood
2
3 class Account < Person
4   attr_accessor :sendmail, :signature
5
6   def initialize h
7     raise ArgumentError, "no name for account" unless h[:name]
8     raise ArgumentError, "no email for account" unless h[:email]
9     super h[:name], h[:email]
10     @sendmail = h[:sendmail]
11     @signature = h[:signature]
12   end
13 end
14
15 class AccountManager
16   include Singleton
17
18   attr_accessor :default_account
19
20   def initialize accounts
21     @email_map = {}
22     @accounts = {}
23     @regexen = {}
24     @default_account = nil
25
26     add_account accounts[:default], true
27     accounts.each { |k, v| add_account v, false unless k == :default }
28   end
29
30   def user_accounts; @accounts.keys; end
31   def user_emails; @email_map.keys.select { |e| String === e }; end
32
33   ## must be called first with the default account. fills in missing
34   ## values from the default account.
35   def add_account hash, default=false
36     raise ArgumentError, "no email specified for account" unless hash[:email]
37     unless default
38       [:name, :sendmail, :signature].each { |k| hash[k] ||= @default_account.send(k) }
39     end
40     hash[:alternates] ||= []
41
42     a = Account.new hash
43     @accounts[a] = true
44
45     if default
46       raise ArgumentError, "multiple default accounts" if @default_account
47       @default_account = a
48     end
49
50     ([hash[:email]] + hash[:alternates]).each do |email|
51       next if @email_map.member? email
52       @email_map[email] = a
53     end
54
55     hash[:regexen].each do |re|
56       @regexen[Regexp.new(re)] = a
57     end if hash[:regexen]
58   end
59
60   def is_account? p; is_account_email? p.email end
61   def is_account_email? email; !account_for(email).nil? end
62   def account_for email
63     if(a = @email_map[email])
64       a
65     else
66       @regexen.argfind { |re, a| re =~ email && a }
67     end
68   end
69 end
70
71 end