Class: ShapeOf::Union
Overview
Union[shape1, shape2, …] denotes that it can be of one the provided shapes.
Class Method Summary collapse
Methods inherited from Shape
#initialize, required?, shape_of?
Constructor Details
This class inherits a constructor from ShapeOf::Shape
Class Method Details
.[](*shapes) ⇒ Object
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 |
# File 'lib/shape_of.rb', line 384 def self.[](*shapes) Class.new(self) do @class_name = "#{superclass.name}[#{shapes.map(&:inspect).join(", ")}]" @shapes = shapes def self.name @class_name end def self.to_s @class_name end def self.inspect @class_name end def self.shape_of?(object, validator: Validator.new(shape: self, object: object)) is_any_shape_of_shape_or_hash_or_array = false is_any_shape_of = @shapes.any? do |shape| if shape.respond_to? :shape_of? is_any_shape_of_shape_or_hash_or_array ||= shape.shape_of?(object) elsif shape.is_a? ::Hash is_any_shape_of_shape_or_hash_or_array ||= Hash[shape].shape_of?(object) elsif shape.is_a? ::Array is_any_shape_of_shape_or_hash_or_array ||= Array[shape].shape_of?(object) elsif shape.is_a? Class object.instance_of?(shape) else object == shape end end if !is_any_shape_of && !is_any_shape_of_shape_or_hash_or_array shape_shapes = @shapes.select do |shape| shape.respond_to?(:shape_of?) || shape.is_a?(::Hash) || shape.is_a?(::Array) end class_shapes = @shapes.select do |shape| !shape.respond_to?(:shape_of?) && !shape.is_a?(::Hash) && !shape.is_a?(::Array) && shape.is_a?(Class) end object_shapes = @shapes.select do |shape| !shape.respond_to?(:shape_of?) && !shape.is_a?(::Hash) && !shape.is_a?(::Array) && !shape.is_a?(Class) end validator.add_error(object.inspect + " is not shape of any of (" + shape_shapes.map(&:inspect).join(", ") + ") or is not instance of any of (" + class_shapes.map(&:inspect).join(", ") + ") or is not equal to (==) any of (" + object_shapes.map(&:inspect).join(", ") + ")") end is_any_shape_of end end end |