Skip to content

Commit

Permalink
implement symmetric validator
Browse files Browse the repository at this point in the history
  • Loading branch information
syphax-bouazzouni committed Feb 28, 2023
1 parent 5168edf commit 810771a
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/goo/validators/enforce.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ def enforce(inst,attr,value)
check Goo::Validators::DataType, inst, attr, value, opt, DateTime
when :float, Float
check Goo::Validators::DataType, inst, attr, value, opt, Float
when :symmetric
check Goo::Validators::Symmetric, inst, attr, value, opt
when Proc
call_proc(opt, inst, attr)
when /^max_/, /^min_/
Expand Down
5 changes: 4 additions & 1 deletion lib/goo/validators/implementations/existence.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ class Existence < ValidatorBase
error_message ->(obj) { "`#{@value}` value cannot be nil"}

validity_check -> (obj) do
not (@value.nil? || self.class.empty?(@value) || self.class.empty_array?(@value))
not self.class.empty_value?(@value)
end

def self.empty_value?(value)
value.nil? || self.empty?(value) || self.empty_array?(value)
end
def self.empty?(value)
empty_string?(value) || empty_to_s?(value)
end
Expand Down
44 changes: 44 additions & 0 deletions lib/goo/validators/implementations/symmetric.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
module Goo
module Validators
class Symmetric < ValidatorBase
include Validator

key :symmetric

error_message ->(obj) {
"symmetric error"
}

validity_check -> (obj) do
return true if Existence.empty_value?(@value)

return Array(@value).select{|x| not self.class.symmetric?(@attr,x, @inst)}.empty?
end

def self.symmetric?(attr, value, source_object)
if self.respond_to?(attr, value)
target_values = self.attr_value(attr, value)
return target_values.any?{ |target_object| self.equivalent?(target_object, source_object)}
end

return false
end

def self.respond_to?(attr, object)
object && object.respond_to?(attr)
end

def self.attr_value(attr, object)
Array(object.send(attr))
end

def self.equivalent?(object1, object2)
if object1.respond_to?(:id) && object2.respond_to?(:id)
object1.id.eql?(object2.id)
else
object2 == object1
end
end
end
end
end

0 comments on commit 810771a

Please sign in to comment.