Class: Hashape::Shape

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

Overview

A template hash representing how a hash should be structured, allowing other hashes to be validated against it.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(shape) ⇒ Shape

Create a new shape.

Parameters:

  • shape (Hash)

    The template hash.



77
78
79
# File 'lib/hashape.rb', line 77

def initialize(shape)
  @shape = shape
end

Instance Attribute Details

#shapeObject (readonly)

Returns the value of attribute shape.



71
72
73
# File 'lib/hashape.rb', line 71

def shape
  @shape
end

Instance Method Details

#matches!(subject) ⇒ Object

Calls #matches? and raises a RuntimeError if it does not return true.

Parameters:

  • subject (Hash)

    The hash to compare the template hash against.



97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/hashape.rb', line 97

def matches!(subject)
  shape.each do |k, spec|
    v = subject[k]
    if v.is_a?(Hash) && spec.is_a?(Hash)
      Shape.new(spec).matches!(v)
    else
      unless spec === v
        raise ShapeMatchError,
          "key #{k} with value #{v} does not match spec #{spec}" \
      end
    end
  end
end

#matches?(subject) ⇒ TrueClass|FalseClass

Returns a boolean indicating whether the given hash matches the template hash which this shape was constructed with.

Parameters:

  • subject (Hash)

    The hash to compare the template hash against.

Returns:

  • (TrueClass|FalseClass)

    A boolean indicating whether the subject hash matches the template hash.



87
88
89
90
91
92
# File 'lib/hashape.rb', line 87

def matches?(subject)
  matches!(subject)
  true
rescue ShapeMatchError
  false
end