summaryrefslogtreecommitdiff
path: root/lib/reserve_usernames/validate.rb
blob: 669c2fb50d74972da493cc7c24af863349dd5a63 (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
module ReserveUsernames::Validate
  def self.included(base)
    base.class_eval do

      validate :check_if_address_is_taken

      protected

      #
      # Only query ReservedUsername if this is a new record.
      # Otherwise, validation will always fail because the address
      # has been taken... by this identity.
      #
      def check_if_address_is_taken
        if new_record? && address
          username = address.split('@').first
          if ReservedUsername.find(username)
            Rails.logger.info("ReserveUsernames - #{username} is taken.")
            errors.add :address, :taken
          end
        end
      rescue ActiveResource::ResourceNotFound
      end

    end
  end
end