initial commit.
[reserve_usernames.git] / lib / reserve_usernames / callbacks.rb
1 module ReserveUsernames::Callbacks
2   def self.included(base)
3     base.class_eval do
4
5       around_create  :create_reservation
6       around_destroy :destroy_reservation
7
8       protected
9
10       def create_reservation
11         if username
12           Rails.logger.info("ReserveUsernames - creating reservation for username '#{username}'.")
13           ru = ReservedUsername.create(:username => username, :reserved_by => owner_string)
14           ru.encode
15           unless ru.persisted?
16             if has_errors?(ru)
17               Rails.logger.error("ReserveUsernames - failed to reserve username (#{ru.errors.error_messages}).")
18               return false
19             else
20               Rails.logger.error("ReserveUsernames - failed to reserve username (remote error).")
21               raise RuntimeError.new('Failed to reserve username. (remote username reservation error)')
22             end
23           end
24         end
25         yield
26         if self.persisted?
27           ru.confirmed = true
28           ru.save
29           return false if has_errors?(ru)
30         end
31       end
32
33       def destroy_reservation
34         ru = ReservedUsername.find(username)
35         ru.deleted = true
36         ru.save
37         yield
38         if self.destroyed?
39           ReservedUsername.delete(username)
40         end
41       rescue ActiveResource::ResourceNotFound
42       end
43
44       def username
45         address ? address.split('@').first : nil
46       end
47
48       #
49       # a label to identify the owner
50       #
51       def owner_string
52         if user && user.id
53           user.id
54         else
55           username
56         end
57       end
58
59       def has_errors?(record)
60         if record.errors.any?
61           record.errors.each do |attr, msg|
62             Rails.logger.error("ReserveUsernames - REMOTE ERROR #{attr}: #{msg}")
63             self.errors.add(attr, msg + " (remote username reservation error)")
64           end
65           true
66         else
67           false
68         end
69       end
70
71     end
72   end
73 end