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
|
# File 'lib/redis/validations/uniqueness.rb', line 6
def self.included(base)
base.class_eval do
class_inheritable_array :unique_fields
self.unique_fields ||= []
class << self
def validates_uniqueness_of(field)
unique_fields << field
end
end
validate do |record|
record.unique_fields.each do |name|
if id_in_use = connection.hget(record.uniqueness_id(name), record.send(name))
if id_in_use != record.id
record.errors.add(name, "must be unique")
end
end
end
end
within_save_block do |record|
record.unique_fields.each do |name|
connection.hdel(record.uniqueness_id(name), record.previous_attributes[name])
connection.hset(record.uniqueness_id(name), record.send(name), record.id)
end
end
within_destroy_block do |record|
record.unique_fields.each do |name|
connection.hdel(record.uniqueness_id(name), record.send(name))
end
end
end
end
|