Class: ShapeOf::Array

Inherits:
Shape
  • Object
show all
Defined in:
lib/shape_of.rb

Overview

Array denotes that it is an array of shapes. It checks every element in the array and verifies that the element is in the correct shape. This, along with Hash, are the core components of this module. Note that a ShapeOf::Array.shape_of?([]) will pass because it is vacuously true for an empty array.

Class Method Summary collapse

Methods inherited from Shape

#initialize, required?

Constructor Details

This class inherits a constructor from ShapeOf::Shape

Class Method Details

.[](shape) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/shape_of.rb', line 232

def self.[](shape)
  Class.new(self) do
    @class_name = "#{superclass.name}[#{shape.inspect}]"
    @shape = shape
    @internal_class = superclass.instance_variable_get(:@internal_class)

    def self.name
      @class_name
    end

    def self.to_s
      @class_name
    end

    def self.inspect
      @class_name
    end

    def self.shape_of?(array, validator: Validator.new(shape: self, object: array))
      return false unless super

      idx = 0
      each_is_shape_of = true
      array.each do |elem|
        validator.push_key("idx_#{idx}".to_sym)

        is_shape_of = if @shape.respond_to? :shape_of?
          @shape.shape_of?(elem, validator: validator)
        elsif @shape.is_a? ::Array
          Array[@shape.first].shape_of?(elem, validator: validator)
        elsif @shape.is_a? ::Hash
          Hash[@shape].shape_of?(elem, validator: validator)
        elsif @shape.is_a? Class
          is_instance_of = elem.instance_of?(@shape)
          validator.add_error(elem.inspect + " is not instance of " + @shape.inspect) unless is_instance_of

          is_instance_of
        else
          is_equal_to = elem == @shape
          validator.add_error(elem.inspect + " is not equal to (==) " + @shape.inspect) unless is_equal_to

          is_equal_to
        end

        validator.pop_key
        idx += 1
        each_is_shape_of &&= is_shape_of
      end
      each_is_shape_of
    end
  end
end

.shape_of?(object, validator: Validator.new(shape: self, object: object)) ⇒ Boolean

Returns:



225
226
227
228
229
230
# File 'lib/shape_of.rb', line 225

def self.shape_of?(object, validator: Validator.new(shape: self, object: object))
  is_instance_of = object.instance_of?(@internal_class)
  validator.add_error(object.inspect + " is not instance of " + @internal_class.inspect) unless is_instance_of

  is_instance_of
end