Sha256: bd40b7edaea5b515f2df079375d1496cf0b596f9697780e1ee69dfe4a2e8244b

Contents?: true

Size: 885 Bytes

Versions: 3

Compression:

Stored size: 885 Bytes

Contents

# frozen_string_literal: true

class Shaped::Shapes::Hash < Shaped::Shape
  def initialize(shape_description)
    unless shape_description.is_a?(Hash)
      raise(Shaped::InvalidShapeDescription, "A #{self.class} description must be a Hash.")
    end

    @hash_description = shape_description.transform_values { |value| Shaped::Shape(value) }
  end

  def matched_by?(hash)
    return false if !hash.is_a?(Hash)

    missing_keys = expected_keys - hash.keys
    return false if missing_keys.any?

    @hash_description.all? do |key, expected_value_shape|
      expected_value_shape.matched_by?(hash[key])
    end
  end

  def to_s
    printable_shape_description =
      @hash_description.map do |key, value|
        "#{key.inspect} => #{value}"
      end.join(', ')

    "{ #{printable_shape_description} }"
  end

  private

  def expected_keys
    @hash_description.keys
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
shaped-0.6.3 lib/shaped/shapes/hash.rb
shaped-0.6.2 lib/shaped/shapes/hash.rb
shaped-0.6.1 lib/shaped/shapes/hash.rb