Skip to content

Commit

Permalink
implement object_type validator with the new DSL
Browse files Browse the repository at this point in the history
  • Loading branch information
syphax-bouazzouni committed Feb 28, 2023
1 parent cd67a52 commit 887653c
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions lib/goo/validators/implementations/object_type.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
module Goo
module Validators
class ObjectType < ValidatorBase
include Validator

key :object_type

error_message ->(obj) {
if @error.eql?(:persistence)
"`#{@attr}` contains non persistent models. It will not save."
else
"`#{@attr}` contains values that are not instance of `#{@model_range.model_name}`"
end
}

validity_check -> (obj) do
values = Array(@value)

unless values.select { |v| !self.class.is_a_model?(v, @model_range) }.empty?
@error = :no_range
return false
end

unless values.select { |v| !self.class.persistent?(v) }.empty?
@error = :persistence
return false
end

return true
end

def initialize(inst, attr, value, model_range)
super(inst, attr, value)
@model_range = model_range
end

def self.is_a_model?(value, model_range)
value.is_a?(model_range) || (value.respond_to?(:klass) && value[:klass] == model_range)
end

def self.persistent?(value)
value.respond_to?(:klass) || value.persistent?
end
end
end
end

0 comments on commit 887653c

Please sign in to comment.