Class: Resto::AssertHash

Inherits:
Object
  • Object
show all
Defined in:
lib/resto/extra/assert_hash.rb

Overview

Note:

This class is only used internally.

AssertHash validates that a Hash only contain valid keys. The purpose is to assert that methods are used with correct arguments.

Class Method Summary collapse

Class Method Details

.keys(hash, *valid_keys) ⇒ Hash

Asserts that keys in the Hash is valid. It also converts String keys to Symbol keys.

Examples:

hash = { :valid => 'I am valid' }
AssertHash.keys(hash, :valid)
 # => { :valid => 'I am valid'}

hash = { 'valid' => 'I am valid' }
AssertHash.keys(hash, :valid)
 # => { :valid => 'I am valid'}

hash = { :invalid => 'I am invalid' }
AssertHash.keys(hash, :valid)
 # => raises ArgumentError

Parameters:

  • hash (Hash)
  • *valid_keys (Symbol, Symbol, ...)

Returns:

  • (Hash)

    string keys are converted to their corresponding Symbols.

Raises:

  • (ArgumentError)

    if the Hash contains unknown key(s).



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/resto/extra/assert_hash.rb', line 33

def self.keys(hash, *valid_keys)
  hash ||= {}

  hash = hash.inject({}) { |h, (key, value)| h[key.to_sym] = hash.delete(key); h }

  known_keys = [valid_keys].flatten
  unknown_keys = hash.keys - known_keys
  unless unknown_keys.empty?
    unknown = "Invalid key(s): #{unknown_keys.join(", ")}"
    known = "Valid key(s): #{known_keys.join(", ")}"
    raise(ArgumentError, "#{unknown} \n #{known}")
  end

  hash
end