Class: MiniDefender::Rules::Unique
Class Method Summary
collapse
Instance Method Summary
collapse
#active?, available?, #bails?, #coerce, #default_value, #defaults?, #error_message, #excluded?, #force_coerce?, #implicit?, #priority, #stops?, #with_message
Constructor Details
#initialize(model, column = nil) ⇒ Unique
Returns a new instance of Unique.
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# File 'lib/mini_defender/rules/unique.rb', line 4
def initialize(model, column = nil)
unless model.is_a?(String) || model.is_a?(Class) && model.ancestors.include?(ActiveRecord::Base)
raise ArgumentError, 'model name must be a string or ActiveRecord::Base'
end
raise ArgumentError, 'Column name must be a string' unless column.is_a?(String) || column.nil?
@model = model
@model = @model.camelcase.constantize if model.is_a?(String)
@column = column
@ignore = nil
@additional_scope = nil
end
|
Class Method Details
.make(args) ⇒ Object
32
33
34
35
36
|
# File 'lib/mini_defender/rules/unique.rb', line 32
def self.make(args)
raise ArgumentError, 'Model and column are required.' unless args.length == 2
self.new(args[0], args[1])
end
|
.signature ⇒ Object
18
19
20
|
# File 'lib/mini_defender/rules/unique.rb', line 18
def self.signature
'unique'
end
|
Instance Method Details
#message(attribute, value, validator) ⇒ Object
48
49
50
|
# File 'lib/mini_defender/rules/unique.rb', line 48
def message(attribute, value, validator)
"The value already exists."
end
|
#passes?(attribute, value, validator) ⇒ Boolean
38
39
40
41
42
43
44
45
46
|
# File 'lib/mini_defender/rules/unique.rb', line 38
def passes?(attribute, value, validator)
@column = attribute.split('.')[-1] if @column.nil?
query = @model.where(@column => value)
query = @additional_scope.call(query) unless @additional_scope.nil?
query = query.where.not(@column => @ignore) unless @ignore.nil?
!query.exists?
end
|
#scope_by(callback) ⇒ Object
27
28
29
30
|
# File 'lib/mini_defender/rules/unique.rb', line 27
def scope_by(callback)
@additional_scope = callback
self
end
|
#should_ignore(value) ⇒ Object
22
23
24
25
|
# File 'lib/mini_defender/rules/unique.rb', line 22
def should_ignore(value)
@ignore = value
self
end
|