Skip to content

Commit d5cedb3

Browse files
committed
Allow proc in validatation conditionals
1 parent 8e56b16 commit d5cedb3

2 files changed

Lines changed: 32 additions & 7 deletions

File tree

motion/validatable.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,21 @@ def validate_for(field, value)
130130
result
131131
end
132132

133+
def must_validate?(validation)
134+
stuff = validation[:if]
135+
return true unless stuff
136+
137+
case stuff
138+
when Symbol then send(stuff)
139+
when Proc then instance_exec(&stuff)
140+
else
141+
fail ArgumentError,
142+
':if requires a Symbol denoting a method or a Proc/lambda'
143+
end
144+
end
145+
133146
def validate_one(field, validation) #nodoc
134-
return true unless validation[:if] ? send(validation[:if]) : true
147+
return true unless must_validate?(validation)
135148

136149
result = true
137150
validation.each_pair do |validation_type, setting|

spec/validation_spec.rb

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ class ValidatableTask
77
:some_day => :string,
88
:some_float => :float,
99
:some_int => :int,
10-
:not_validate => :string
10+
:if_with_proc => :string,
11+
:if_with_sym => :string
1112

1213
validate :name, :presence => true
1314
validate :name, :length => 2..10
@@ -16,7 +17,8 @@ class ValidatableTask
1617
validate :some_day, :length => 8..10
1718
validate :some_float, :presence => true
1819
validate :some_int, :presence => true
19-
validate :not_validate, :presence => true, :if => :false_condition_method
20+
validate :if_with_proc, :presence => true, :if => -> { if_with_proc == 'unexpected' }
21+
validate :if_with_sym, :presence => true, :if => :false_condition_method
2022

2123
def false_condition_method
2224
false
@@ -31,14 +33,24 @@ def false_condition_method
3133
:some_day => '12-12-12',
3234
:some_float => 1.080,
3335
:some_int => 99,
34-
:not_validate => 'Never validated column'
36+
:if_with_proc => 'Never validated column',
37+
:if_with_sym => 'Never validated column'
3538
}
3639
end
3740

3841
describe 'conditional validation' do
39-
it 'does not validate if condition method returns false' do
40-
task = ValidatableTask.new(@valid_tasks.except(:not_validate))
41-
task.valid?.should == true
42+
context 'with conditional by method' do
43+
it 'does not validate if condition returns false' do
44+
task = ValidatableTask.new(@valid_tasks.except(:if_with_sym))
45+
task.valid?.should == true
46+
end
47+
end
48+
49+
context 'with conditional by proc' do
50+
it 'does not validate if condition returns false' do
51+
task = ValidatableTask.new(@valid_tasks.except(:if_with_proc))
52+
task.valid?.should == true
53+
end
4254
end
4355
end
4456

0 commit comments

Comments
 (0)