Class: ShapeOf::Pattern

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

Overview

Matches a Regexp against a String using Regexp#match?. Pretty much a wrapper around Regexp because a Regexp instance will be tested for equality in the ShapeOf::Hash and ShapeOf::Array since it’s not a class.

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

.[](shape) ⇒ Object

Raises:

  • (TypeError)


481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/shape_of.rb', line 481

def self.[](shape)
  raise TypeError, "Shape must be #{Regexp.inspect}, was #{shape.inspect}" unless shape.instance_of? Regexp

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

    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))
      unless object.instance_of?(String)
        validator.add_error(object.inspect + " is not instance of " + String.inspect)
        return false
      end

      does_regexp_match = @shape.match?(object)
      validator.add_error(object.inspect + " does not match " + @shape.inspect) unless does_regexp_match
      does_regexp_match
    end
  end
end